Inevitably, as you progress to more complex scripts, your scripts will need to be able to make decisions and take separate actions based upon those conditions. For this, VBScript provides conditional statements.
Conditional statements route code execution based upon the value of some expression. These conditions typically involve some comparison and are evaluated to either True or False. The conditional statement then branches off code execution accordingly.
Imagine the following scenario:
You're writing a script to open or close a door. Which action should be performed is strictly dependent upon the current state of the door. In other words, you can't open a door that's already open! So some code might look like this.
Set objDoor = CreateObject("My.Door")
If objDoor.IsOpen Then
objDoor.Close
Else
objDoor.Open
End If
In this hypothetical example we have an object name objDoor that represents our door. This object class has Open and Close methods to perform our action as well as an IsOpen property that returns a value of True if the door is currently open.
I've made use of an IF statement to check the value of the IsOpen property. If it evaluates to True the immediate code block is executed. If it evaluates to False, the Else block is executed. Code would then continue with the line immediately following the End If statement.
Of course, this is an extremely simplified example. The If statement offers some more advanced flexibility and there are several ways to construct much more intricate expressions. To begin, let's take a look at the If statement up close.
The If statement is used to execute whenever a certain condition is true. This condition is supplied in the form of an expression and must be able to be evaluated as a Boolean value. The syntax for an If statement is very simple although it does contain some optional keywords for making more complex decisions.
If expression Then
code
[Elseif expression Then
code]
[Else
code]
End If
You are only required to have the opening If...Then and closing End If statements. You may have multiple Elseif blocks but only one of any of the others.
Expression is some conditional expression that can be evaluated to either True or False. We'll get into these in greater detail later in this article. VBScript provides several functions designed with conditional expression in mind to make things easier.
Execution works from top to bottom. VBScript will execute the code block associated with the first condition that can be met. Once that block completes execution it then moves to the first line after the closing End If statement.
Here's an example of an If statement that checks to see if a supplied number is positive, negative, or zero.
intNumber = -1
If intNumber = 0 Then
WScript.Echo "Number equals 0"
ElseIf intNumber > 0 Then
WScript.Echo "Number is positive"
Else
WScript.Echo "Number is negative"
End If
We start by creating a variable with the integer value of -1. As we enter the If statement, the first expression is evaluated. Since -1 is not equal to 0, it moves to the next branch, the Elseif statement. Since this condition returns false as well, it continues to the Else branch. This condition is satisfied and its containing code is executed. Our script kindly displays "Number is negative."
In this case, all of our expressions were comparisons. We'll take a look at the various comparison operators a little later.
"But what happens if none of the conditions are satisfied?" you ask.
Simple. Nothing; none of the code blocks are executed. This is a handy device in the event that you want some code executed only when a specific condition exists.
There is also a shorthand syntax for the If statement but it does have some limitations. You cannot use it to execute multiple statements when a condition is met, and you may not use any of the optional keywords. It looks like this:
If expression Then code
This shorthand syntax must appear on a single line. When you are using the shorthand syntax you may drop the closing End statement.
If strColor = "blue" Then setColor(blue)
Here our sample shows a very simple If statement that checks to see if a variable is set to "blue." If so, it calls the setColor function. Otherwise, it does nothing and code execution continues.
You can make more complex decisions by nesting multiple If statements within each other.
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
[Casevalue
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.
When discussing conditional statements, it's important to discuss conditional expressions. These are the expressions that allow conditional statements to function.
Conditional expressions always return a Boolean value of either True of False depending upon whether the expression can be successfully evaluated.
The most common type of conditional expression is an equality test. This tests to see if the value of one variable is equal to the value of another. Equality is determined based upon the variable type being used. For example, two strings must contain the same characters or two integers must contain the same values.
You can use the NOT keyword to indicate the converse of an expression. In other words, NOT returns the opposite of whatever the expression evaluates to.
Each of the elements in an expression may be either a variable or a literal. In other words, any of the following are perfectly acceptable.
strColor = "red" returns True if strColor contains "red"
strColor1 = strColor2 returns either True or False
"red" = "blue" returns False
NOT "blue" = "blue" returns False
While it's completely obvious that some of these will return False, they are nonetheless acceptable.
You can also make decisions based upon more than one conditional expression using logical operators. The logical operators are AND and OR.
When using logical operators, a single value is returned based upon the conditions provided. When using AND, True is returned only if both supplied conditions evaluate to True, and False otherwise. When using OR, True is returned if either (or both) of the conditions returns True.
"blue" = "blue" AND "red" = "red returns True
"blue" = "blue" AND "blue" = "red" returns False
NOT "blue" = "red" AND NOT 3 = 4 returns True
"blue" = "blue" OR "red"="red" returns True
"blue" = "blue" OR "blue" = "red" returns True
5 = 4 OR 3 = 2 returns False
In the above examples, you can see how the logical operators can be used to combine expressions. They are evaluated as follows:
True AND True returns True
True AND False returns False
False AND False returns False
True OR True returns True
True OR False returns True
False OR False returns False
Multiple logical operators are evaluated from left to right. This can produce some unwanted results. As in algebra, you can use a pair of parenthesis to control the order of operations. Take the following for example.
Condition1 AND Condition2 OR Condition3
This expression will evaluate to True if Condition1 and Condition2 are both true OR if only Condition3 is true. (It also evaluates to true if all three conditions are true).
That 's fine, if that's what you wanted. But what if you were trying to evaluate whether Condition1 existed with either of the other two?
Condition1 AND (Condition2 OR Condition3)
By using parenthesis, we are now forcing the OR operator to evaluate before the AND. This achieves our goal and will only return true if Condition1 is true along with either or both of the other conditions.
This seems a little confusing at first, but you will begin to get the hang of things much more quickly once you start putting these into real-world use.
For the sake of brevity, I haven't gone into much detail surrounding conditional expressions. Be aware that they may use any of the available operators such as < (less than), > (greater than), or even bitwise operators such as XAND and XOR.
These are far beyond the scope of this article, so stay tuned for a future release dedicated strictly to VBScript operators. Until next time, keep coding!