Conditional Statements Tutorial

Lesson 1
Tutorials - Page 1 - Page 2 - Page 3 - Page 4 - Page 5 - Page 6 - Page 7 - Page 8 - Page 9 - Page 10

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


After every condition, comes the line that will be executed
if the condition will be "True".

For example, the line:

Case "elvis": MsgBox "your name is elvis"

Is the same as:

If (VariableName = "elvis") Then   
    MsgBox "your name is elvis"
End If



After all conditions, comes the Else condition (It's
optional condition, and you can omit it if you want):
Case Else:

This condition will be executed ONLY if none
of the conditions above was executed.

After all of the conditions, the statement closed with   End Select


Note that you can have more than 1 line to executed
in each condition. For example:

Dim Name As String
Name = InputBox("Please enter your name")
Select Case Name
    Case "elvis": MsgBox "your name is elvis"
                  MsgBox "you are the king!" 
                  MsgBox "I didn't know you are alive!"
    Case "tim": MsgBox "your name is tim"
    Case "john": MsgBox "your name is john"
    Case Else: MsgBox "I don't know you"
End Select


Back  Tutorials