Chapter 10: VBA Programming Fundamentals
403
When you have many conditions to test, the If...Then...ElseIf...Else conditions can get
rather unwieldy. A better approach is to use the Select Case...End Select construct.
The Select Case...End Select statement
VBA offers the Select Case statement to check for multiple conditions. Following is the general
syntax of the Select Case statement:
Select Case Expression
Case Value1
[Action to take when Expression = Value1]
Case Value2
[Action to take when Expression = Value2]
Case ...
Case Else
[Default action when no value matches Expression]
End Select
Notice that the syntax is similar to that of the If...Then statement. Instead of a Boolean condi-
tion, the Select Case statement uses an expression at the very top. Then, each Case clause tests
its value against the expression’s value. When a Case value matches the expression, the program
executes the block of code until it reaches another Case statement or the End Select statement.
VBA executes the code for only one matching Case statement.
Note
If more than one Case statement matches the value of the test expression, only the code for the first match
executes. If other matching Case statements appear after the first match, VBA ignores them.
Figure 10.19 shows Select...Case used by frmDialogContactPrint to decide which of
several reports to open.
FIGURE 10.19
Using the Select Case statement