Looping Statements in VBScript - Conditional Loops
(Page 3 of 4 )
Conditional loops are constructed using the Do…Loop statements. VBScript provides the While and Until keywords to determine whether a loop should execute when a condition is true or false, respectively.
The conditional statement can be any statement or calculation that evaluates to either True or False. It can even be as simple as a Boolean value.
As you will see, the syntax of the Do…Loop statement is very flexible. I’ll demonstrate the most widely accepted versions first.
Do While | Until statement
' Code to be repeated
Loop
You must supply either the While or Until keyword followed by a conditional statement. Any conditional statement will work as long as it can be evaluated to either True or False. Comparisons and equality tests are the most common type of conditional statements found in Do loops.
x = 1
Do While x <> 5
WScript.Echo x
x = x + 1
Loop
The code above will continue outputting the value of x as long as it does not equal 5. In other words it will execute “While x does not equal 5”. This continues to execute as long as the condition is met providing the following output:
1
2
3
4
To see how the Until keyword processes false statements, we can modify the conditional statement above to its converse.
x = 1
Do Until x = 5
WScript.Echo x
x = x + 1
Loop
This loop will continue to execute “Until x equals 5.” A closer look shows that this loop will only continue to execute as long as the condition evaluates to false.
x = 1
Do Until x = 5
WScript.Echo x
x = x + 2
Loop
Take care when constructing your conditions. Since x can never equal 5, the above code creates an endless or “infinite” loop because the condition can never be met.
The alternative Do…Loop syntax places the keyword and conditional statement in the closing statement instead. While this is acceptable, it’s not widely used.
x = 1
Do
WScript.Echo x
x = x + 1
Loop Until x = 5
Next: More On Loops >>
More BrainDump Articles
More By Nilpo