Looping
Looping Statements in VBScript
Looping statements are used to execute the same block of code repeatedly for a fixed number of times or until a specific condition is met.
VBScript provides four types of looping statements:
For…Next loop – Executes code a specific number of times
For Each…Next loop – Executes code for each element in an array or collection
Do…Loop statement – Repeats code while or until a condition is met
While…Wend statement – Not recommended; use Do…Loop instead
For…Next Loop
The For…Next loop is used when you know in advance how many times the loop should run.
The For statement initializes the counter variable and defines the start and end values
The Next statement increments the counter by 1 each time the loop runs
Example:
<% For i = 0 To 5 Response.Write("The number is " & i & "
") Next %>
Using the Step Keyword
The Step keyword allows you to control how much the counter variable increases or decreases after each iteration.
Increasing the Counter
For i = 2 To 10 Step 2 some code Next
In this case, the value of i increases by 2 each time.
Decreasing the Counter
To decrease the value, use a negative Step and ensure the end value is smaller than the start value.
For i = 10 To 2 Step -2 some code Next
Here, the value of i decreases by 2 on each loop.
Exiting a For…Next Loop
You can terminate a For…Next loop early using the Exit For statement.
For i = 1 To 10 If i = 5 Then Exit For some code Next
The loop stops when i reaches 5.
For Each…Next Loop
The For Each…Next loop is used to iterate through all elements of an array or collection without using an index.
Example:
<% Dim cars(2) cars(0) = "Volvo" cars(1) = "Saab" cars(2) = "BMW" For Each x In cars Response.Write(x & "
") Next %>
Each element in the cars array is printed one by one.
Do…Loop Statement
Use a Do…Loop when the number of iterations is not known in advance.
A Do…Loop can repeat code:
While a condition is true
Until a condition becomes true
Do…Loop While Condition is True
Condition Checked Before Loop
Do While i > 10 some code Loop
If i is less than or equal to 10, the loop will not execute at all.
Condition Checked After Loop
Do some code Loop While i > 10
This loop will execute at least once, even if the condition is false initially.
Do…Loop Until Condition Becomes True
Condition Checked Before Loop
Do Until i = 10 some code Loop
If i is already 10, the loop will not run.
Condition Checked After Loop
Do some code Loop Until i = 10
This loop executes at least one time, even if i equals 10.
Exiting a Do…Loop
You can stop a Do…Loop early using the Exit Do statement.
Do Until i = 10 i = i - 1 If i < 10 Then Exit Do Loop
The loop continues as long as i is not equal to 10 and remains greater than 10.