Do..Loop - VBScript
Overview
The Do..Loop
command in VB Script creates a loop structure for executing a set of statements repeatedly until a specified condition is met. It is useful when the number of iterations is unknown or when you need to repeat a block of code based on a loop counter.
Syntax
Do [While | Until] condition
[statements]
Loop
Parameters:
- condition: Determines whether to continue the loop. Can be a logical expression or a comparison.
- While: Executes the loop as long as the condition remains true.
- Until: Executes the loop until the condition becomes true.
- statements: The code to be executed within the loop.
Options/Flags
There are no options or flags associated with the Do..Loop
command.
Examples
Simple loop with a counter:
Dim i
Do While i < 10
Debug.Print i
i = i + 1
Loop
Loop until a condition is met:
Do Until InputBox("Enter 'Quit' to exit") = "Quit"
' Inside the loop...
Loop
Common Issues
- Ensure that the loop condition eventually evaluates to
False
(Do While
) orTrue
(Do Until
) to prevent infinite loops. - Avoid using
Exit For
orExit Do
within a nested loop, as it may exit the wrong loop.
Integration
The Do..Loop
command can be combined with other VB Script constructs, such as Select Case
or If..Then
statements, for more complex loop control.
Related Commands
For..Next
: A more straightforward loop structure with a known number of iterations.Do While..Loop
: Similar toDo..Loop
but only executes the loop if the condition is initially true.