Conditional Statements in VBScript - The IF statement
(Page 2 of 4 )
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.
Next: Select Case >>
More BrainDump Articles
More By Nilpo