17 November, 2005
Control Structures in VBScript
Conditional Statements
If Statement
If Age = 100 Then
MsgBox "Congratulations!"
An If statement first checks to see if the specified condition evaluates to True or False. If it evaluates to True, then
it evaluates a set of statements. In the example above, the "Congratulations!" message box is only displayed if Age = 100, i.e. if Age is equal to 100.
If Age = 100 Then
MsgBox "Congratulations!"
BuyBirthdayPresent = True
End If
When multiple statements need to be executed, an End If statement needs to be inserted at the end.
If Age = 100 Then
MsgBox "Congratulations!"
Else
MsgBox "You're still a young chicken!"
End If
Now we introduce the Else construct. If the condition evaluates to True, the first set of statements are executed. Otherwise, the set
of statements after the Else statement are executed.
Select Case
Select Case is useful when there are many conditions to be checked.
Syntax
Select Case expression
Case value1
Case value2
...
Case Else
End Select
With Select Case, expression is checked for equality against each of value1, value2, ... until a match is found. If no values match, then the Case Else statement is executed.
Loops
You will often need to repeat a set of statements in VBScript. This is done using control structures known as loops.
For Loops
This type of loop is used to repeat a set of statements using a counter. Here is the syntax.
For counter = start to finish
...
Next
The counter variable begins at the number specified by start and counts up by one each time the enclosed code is executed, until it reaches finish.
You can also change the increment value of the loop using the Step keyword.
For counter = start to finish Step increment
...
Next
To make the counter decrement you can use a negative Step value.
While Loops
This structure is used to repeat a set of statements while a particular condition is true.
Do While condition
...
Loop
A close relative of the while loop has this syntax:
Do
...
Loop Until condition
This simply defers the decision making to the end of the loop. These loops will always be executed at least once, and the condition is tested after the first iteration.
Infinite Loops
Beware of using conditions that are always True in your While loops, or somehow using an increment of 0 in your For loops! This will make the loop execute for ever. Many browsers notice this and allow the user to terminate the script. It can be annoying if it causes the whole browser to lock up though, so be careful.