Conditional Statements in VBScript - Select Case
(Page 3 of 4 )
VBScript provides another method for making decisions as well. This is the Select Case statement. It acts in much the same way as an IF statement but it allows you to make a decision between several alternatives for a single expression.
Select Case expression
Case value
code
[Case value
code]
[Case Else
code]
End Select
The opening statement must contain a conditional expression without any operator. Each Case has a possible value for that expression. This works off of an equality comparison. You may list as many possible cases as you need. If included, Case Else is executed if no other condition is met.
Select Case strColor
Case "blue"
WScript.Echo "Color is blue"
Case "red"
WScript.Echo "Color is red"
Case "green"
WScript.Echo "Color is green"
Case Else
WScript.Echo "Color is not blue, red, or green"
End Select
In this example, we're checking the value of the strColor variable. Code is executed based upon what color strColor is equal to. Here is the equivalent If statement.
If strColor = "blue" Then
WScript.Echo "Color is blue"
ElseIf strColor = "red" Then
WScript.Echo "Color is red"
ElseIf strColor = "green" Then
WScript.Echo "Color is green"
Else
WScript.Echo "Color is not blue, red, or green"
End If
Select Case allows a much simpler way to make several comparisons to the same expression and makes for easier readability.
Next: Conditional Expressions >>
More BrainDump Articles
More By Nilpo