Select Case statement is a useful and more readable substitute for the VBScript
If...Elseif statement. It allows you to execute one out of many blocks of code depending on the value of a variable.
While searching for example uses of this statement, I noticed that most of the examples available on the internet do not describe the complete syntax and usage of the statement. According to the MSDN VBScript reference, the syntax of the
Select Case statement is:
Select Case testexpression [Case expressionlist-n [statements-n]] . . . [Case Else [elsestatements-n]] End Select . . . expressionlist-n Required if Case appears. A comma delimited list of one or more expressions. . . .
Notice that it says a comma delimited list of one or more expressions. This means you can select one block of code for more than one value. The following code demonstrates an example usage of the Select Case statement in ASP + VBScript environment.
<% ' ' Assumes that a variable called "Rating" is declared and assigned an integer value ' Select Case Rating Case 1 Response.Write "Poor" Case 2, 3, 4 Response.Write "Below Average" Case 5, 6 Response.Write "Average" Case 7, 8, 9 Response.Write "Good" Case 10 Response.Write "Excellent" Case Else Err.Raise vbObjectError + &H0911, "Custom Error Handler", "Rating must be an integer between 1 and 10" End Select %>
Select Case Statement Trick: Using "Select Case True"
Upon execution, the VBScript interpreter compares the testexpression with each case expression until a match is found. The testexpression could be specified as
true and the case expressions can contain expressions that evaluate to true or false (for example:
a < b And b < c;
a > 0). This allows you to write complex logic relatively easily. The following VBScript example checks whether a number is even or odd using this technique.
<% ' ' Assumes that a variable called "Number" is declared and assigned an integer value ' Select Case True Case Number Mod 2 = 0 Response.Write Number & " is an Even Number" Case Number Mod 2 = 1 Response.Write Number & " is an Odd Number" End Select %>
This statement is quite similar to the C language's
switch case statement. However, there is NO
break statement or its equivalent
Exit Case or
Exit Select available in VBScript.