Using "Select Case"
The
"Select Case" conditional statement
is very useful when you have in your
conditional
statement many conditions.
For example, in the last page
we had the following code:
Dim Name As String
Name =
InputBox("Please enter your name")
If (Name = "elvis") Then
MsgBox "your name is elvis"
ElseIf (Name = "tim") Then
MsgBox
"your name is tim"
ElseIf (Name = "john") Then
MsgBox "your
name is john"
ElseIf (Name = "steve") Then
MsgBox "your name
is steve"
Else
MsgBox "I don't know you"
End If
When you have many conditions, the "If
Statement"
become too bulky.
In this case, you can use instead of it the
"Select Case Statement".
The following "Select Case Statement" is do EXACTLY
the same
thing as the code above:
Dim Name As String
Name =
InputBox("Please enter your name")
Select Case Name
Case "elvis": MsgBox "your name is elvis"
Case "tim":
MsgBox "your name is tim"
Case "john": MsgBox "your name
is john"
Case "steve": MsgBox "your name is
steve"
Case Else: MsgBox "I don't know you"
End
Select
The "Select Case" syntax is very
simple:
It Begins with:
Select Case VariableName
Then comes the conditions.
Every condition has
"Case" before it, and ":" after it.
The "Select Case" conditions are little
different from the "If" conditions:
The Select Case Condition | The equivalent "If" Condition |
Case "elvis" | VariableName = "elvis" |
Case Is <> "elvis" | VariableName <> "elvis" |
Case 5 | VariableName = 5 |
Case Is <> 5 | VariableName <> 5 |
Case Is > 5 | VariableName > 5 |
Case Is >= 5 | VariableName >= 5 |
Case Is < 5 | VariableName < 5 |
Case Is <= 5 | VariableName <= 5 |