172 Part II Programming Fundamentals
statements executed if value3 matches variable
...
Case Else
statements executed if no match is found
End Select
A Select Case structure begins with the Select Case keywords and ends with the End Select
keywords. You replace variable with the variable, property, or other expression that is to
be the key value, or test case, for the structure. You replace value1, value2, and value3 with
numbers, strings, or other values related to the test case being considered. If one of the
values matches the variable, the statements below the Case clause are executed, and then
Visual Basic jumps to the line after the End Select statement and picks up execution there.
You can include any number of Case clauses in a Select Case structure, and you can include
more than one value in a Case clause. If you list multiple values after a case, separate them
with commas.
The following example shows how a Select Case structure could be used to print an
appropriate message about a person’s age and cultural milestones in a program. Since the
Age variable contains a value of 18, the string “You can vote now!” is assigned to the Text
property of the label object. (You’ll notice that the “milestones” have a U .S. slant to them;
please customize freely to match your cultural setting .)
Dim Age As Integer
Age = 18
Select Case Age
Case 16
Label1.Text = "You can drive now!"
Case 18
Label1.Text = "You can vote now!"
Case 21
Label1.Text = "You can drink wine with your meals."
Case 65
Label1.Text = "Time to retire and have fun!"
End Select
A Select Case structure also supports a Case Else clause that you can use to display a
message if none of the preceding cases matches the Age variable. Here’s how Case Else
would work in the following example—note that I’ve changed the value of Age to 25 to
trigger the Case Else clause:
Dim Age As Integer
Age = 25
Select Case Age
Case 16
Label1.Text = "You can drive now!"
Case 18
Label1.Text = "You can vote now!"
Case 21
Label1.Text = "You can drink wine with your meals."