Switch 函数Switch function

计算表达式的列表并返回与列表中第一个结果为 True 的表达式关联的 Variant 值或表达式。Evaluates a list of expressions and returns a Variant value or an expression associated with the first expression in the list that is True.

语法Syntax

切换(expr-1, value-1, [ expr-2, value-2..., [ expr-n, value-n ]])Switch(expr-1, value-1, [ expr-2, value-2…, [ expr-n, value-n ]])


Switch 函数的语法包含以下部分:The Switch function syntax has these parts:

PartPart 说明Description
exprexpr 必需。Required. 要计算的变体表达式Variant expression that you want to evaluate.
valuevalue 必需。Required. 要在相应表达式为 True 时返回的值或表达式。Value or expression to be returned if the corresponding expression is True.

备注Remarks

Switch 函数参数列表由多对表达式和值组成。The Switch function argument list consists of pairs of expressions and values. 从左到右计算表达式,并返回与计算结果为 True 的第一个表达式关联的值。The expressions are evaluated from left to right, and the value associated with the first expression to evaluate to True is returned.

如果各部分未能正确配对,则会发生运行时错误If the parts aren't properly paired, a run-time error occurs. 例如,如果 expr-1TrueSwitch 将返回 value-1For example, if expr-1 is True, Switch returns value-1. 如果 expr-1False,但 expr-2TrueSwitch 将返回 value-2 等等,依此类推。If expr-1 is False, but expr-2 is True, Switch returns value-2, and so on.

Switch 在以下情况下将返回 Null 值:Switch returns a Null value if:

  • 没有表达式的结果为 TrueNone of the expressions is True.

  • 结果为 True 的第一个表达式的相应值为 NullThe first True expression has a corresponding value that is Null.

Switch 计算所有表达式,尽管它只返回其中一个表达式的值。Switch evaluates all of the expressions, even though it returns only one of them. 因此,应注意不需要的负效应。For this reason, you should watch for undesirable side effects. 例如,如果任何表达式的计算导致除零错误,则会发生错误。For example, if the evaluation of any expression results in a division by zero error, an error occurs.

示例Example

此示例使用 Switch 函数返回与某个城市名称匹配的语言名称。This example uses the Switch function to return the name of a language that matches the name of a city.

Function MatchUp(CityName As String)
    Matchup = Switch(CityName = "London", "English", CityName _
                    = "Rome", "Italian", CityName = "Paris", "French")
End Function

另请参阅See also

支持和反馈Support and feedback

有关于 Office VBA 或本文档的疑问或反馈?Have questions or feedback about Office VBA or this documentation? 请参阅 Office VBA 支持和反馈,获取有关如何接收支持和提供反馈的指南。Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.