Switch Function

Named Arguments

No

Syntax

Switch(expr-1, value-1[, expr-2, value-2 ... [, _
       expr-n,value-n]])

expr

Use: Required

Data Type: Variant

A number of expressions to be evaluated.

value

Use: Required

Data Type: Variant

An expression or value to return if the associated expression evaluates to True.

Return Value

A Variant value or expression.

Description

Evaluates a list of expressions and, on finding the first expression to evaluate to True, returns an associated value or expression.

Rules at a Glance

  • A minimum of two expression/value pairs is required; additional pairs are optional.

  • Expressions are evaluated from left to right.

  • If none of the expressions are True, the Switch function returns Null.

  • Although Switch returns only the first True expression's associated value, all expressions in the list are evaluated. This means that no performance gains result from placing expressions that are more likely to evaluate to True earlier in the list. It also means that any expression is capable of raising a run-time error.

  • value can be a constant, a variable, or an expression.

Example

The GetTextColor function uses the Switch function to return a color value that depends on the sign of the long integer passed to it as a parameter.

Private Function GetTextColor(lValue As Long) As Long

GetTextColor = Switch(lValue > 0, vbBlue, lValue = 0, _
                      vbBlack, lValue < 0, vbRed)

End Function

Programming Tips and Gotchas

The Switch function can prove to be an efficient alternative to ...

Get VB & VBA in a Nutshell: The Language now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.