The VBA Switch function evaluates a list of Boolean expressions and returns a value associated with the first true expression.
The syntax of the function is:
Where the function arguments are:
|-||One or more boolean expressions to be evaluated.|
|-||The values to be returned if the corresponding Expr-1, [Expr-2], etc. is the first True expression.|
If none of the supplied expressions evaluate to True, the Switch function returns the value Null.
' Return a surname corresponding to a supplied forename.fname = "Lucy"
Dim fname As String
sname = Switch( fname = "Mary", "Jones", fname = "Joseph", "Johnson", fname = "Lucy", "Smith" )
' sname is now equal to "Smith".
In the above call to the Switch function, the third expression,
fname="Lucy" is the first expression to evaluate to True. Therefore, the function returns the associated surname, "Smith".
' Return a name, depending on an integer value.i = 12
Dim i As Integer
fname = Switch( i < 10, "Mary", i < 20, "Joseph", i < 30, "Lucy" )
' fname is now equal to "Joseph".
In the above call to the Switch function, the second expression,
i<20 is the first expression to evaluate to True. Therefore, the function returns the associated name, "Joseph".
Note that both the second expression
i<20 and the third expression,
i<30 evaluate to True. However, the Switch function only returns the value corresponding to the first True expression in the supplied list.