When we need to run the group of code several times, we can use the following looping statements in VBScript.
For Each…Next Statement,
Do…Loop Statement and
Let’s discuss one by one with the example.
We use the For…Next statement to execute a block of code a specified number of times. See the example:
Dim end end = 5 Dim count For count = 1 to end document.write (count & " ") Next
In the For…Next loop, VBScript assigns start to count = 1 Before running the statement block, it compares count to end. If count is already past the end value, the For loop terminates and goes to next of the For…Next loop. Otherwise, the statement block runs.
For Each…Next Statement
We use the For Each…Next statement to execute a block of code for each element in an array or collection. See the following example:
Dim arrCity(3) arrCity(0) = "New Delhi" arrCity(1) = "Londan" arrCity(2) = "New York" arrCity(3) = "Paris" Dim city For Each city in arrCity document.write (city & " ") Next
Do…Loop Statement repeats the execution a block of code until the specific condition becomes True.
See the following example, the Do loop repeats execution of the statements until the count variable is greater than 5.
Dim count count= 0 Do document.write(count & " ") count= count+ 1 Loop Until count> 5
In this statement we use the certain condition expression with the while statement. While…Wend Statement executes a block of the code as long as a given condition is True.
See the following example to use the While…Wend Statement.
Dim count count= 0 While count < 5 count = count + 1 document.write(count & " ") Alert count Wend
Previous chapter:Use operators in VBScript