VBScript Loops
Loop statement
Loop statements are used to run the same block of code a specified number of times. Looping statements are used to run the same block of code a specified number of times.
In VBScript, we can use four loop statements:
- **For...Next Statement ** - runs a block of code a specified number of times
- **For Each...Next Statement ** - runs a block of code for each item in a collection or each element in an array
- **Do...Loop Statement ** - runs a loop while a condition is true or until a condition is true
- **While...Wend Statement ** - do not use this statement - use the Do...Loop statement instead
For...Next Loop
Please use the For...Next The statement runs a block of code a specified number of times.
For The statement specifies the counter variable (i) along with its initial and end values.Next The statement increments the variable by a step value of 1 (i)。
Example
Try it »
Step keyword
With the ** Step** keyword, you can specify the step value by which the counter variable increments or decrements.
In the following example, the counter variable (i) has an increment step value of 2 on each loop.
For i=2 To 10 Step 2
some code
Next
To decrement the counter variable, you must use a negative Step value. You must also specify an end value that is less than the start value.
In the following example, the counter variable (i) has a decrement step value of 2 on each loop.
For i=10 To 2 Step -2
some code
Next
Exiting For...Next
You can exit a For...Next statement with the Exit For keyword.
For i=1 To 10
If i=5 Then Exit For
some code
Next
For Each...Next Loop
For Each...Next Repeats a block of code for each item in a collection or each element in an array.
Example
Try it »
Do...Loop
If you do not know how many times to repeat, you can use the Do...Loop statement.
The Do...Loop statement repeats a block of code until a condition is true or becomes true.
Repeat code until a condition is true
You can use the While keyword to check the condition of a Do...Loop statement.
Do While i>10
some code
Loop
If ** i** equals 9, the code inside the above loop will stop executing.
Do
some code
Loop While i>10
The code inside this loop will be executed at least once, even if ** i** is less than 10.
Repeat code until a condition becomes true
You can use the Until keyword to check the condition of a Do...Loop statement.
Do Until i=10
some code
Loop
If ** i** equals 10, the code inside the above loop will stop executing.
Do
some code
Loop Until i=10
The code inside this loop will be executed at least once, even if ** i** equals 10.
Exiting Do...Loop
You can exit a Do...Loop statement with the Exit Do keyword.
Do Until i=10
i=i-1
If i<10 Then Exit Do
Loop
The code inside this loop will be executed as long as i is not 10 and i is greater than 10.
More examples (IE only)
Looping through headings
How to loop through the six headings in html.
Do...While loop
How to make a simple Do...While loops.