In today’s lesson, I’ll show you how to use Conditional Statements in VbScript. Conditional statements are very important in any programming, so it is in VBScripting. We have a choice of 2 statements in VBScript If..Then...Else and Select...Case.
If…then
If you want to execute a set of instructions only when a certain condition is met, you can use an If…then condition. You can control the execution of instructions based on a true condition, as follows:
if condition = True Then
A = B
End If
You can also use this form:
if Not condition Then
A <> B
End If
You can extend the If…then condition with the Else and ElseIf statements. The Else statement offers an alternative when a condition you specified isn't met. Here's the structure of an if…then…else condition:
if homeRun = True Then
Msgbox "The condition has been met."
Else
Msgbox "The condition has not been met."
End If
To add more conditions, you can use the ElseIf statement. In this way, each condition you add to the code is checked for validity. Here's an example that uses the ElseIf statement:
if firstValue < 0 Then
Msgbox "The value is less than zero."
ElseIf firstValue = 0 Then
Msgbox "The value is equal to zero."
ElseIf firstValue = 1 Then
Msgbox "The value is equal to one."
ElseIf firstValue = 2 Then
Msgbox "The value is equal to two."
Else
Msgbox "The value is greater than 4."
End If
Select Case
Checking for multiple conditions with the ElseIf structure can be tedious. When you want to check more than three conditions, you should probably use the Select Case statement. In the Select Case structure, the last example in the previous section can be transformed into code that's clearer and easier to understand:
Select Case firstValue
Case < 0
Msgbox "The value is less than zero."
Case 0
Msgbox "The value is equal to zero."
Case 1
Msgbox "The value is equal to one."
Case 2
Msgbox "The value is equal to two."
Case 3
Msgbox "The value is equal to three."
Case 4
Msgbox "The value is equal to four."
End Select
If you compare the ElseIf example and the Select Case example, you can see that the Select Case example requires less code and has a simpler structure. You can apply this same structure any time you want to check for multiple conditions. Here's another example of Select Case:
Select Case Abbrev
Case "HTML"
Message "The HyperText Markup Language."
Case "SGML"
Message "The Standard Generalized Markup Language."
Case "VRML"
Message "The Virtual Reality Modeling Language."
Case Else
Message "You have entered an abbreviation not known to the system."
End Select