Looping permits you to execute a sequence of programming statements again and again. Some of the loops repeat a sequence of statements until a condition is False; others repeat statements until a condition is True; finally some loops repeat a sequence of statements a predetermined number of times.
There are 4 looping statements existing in VBScript:
For…Next
For Each…Next
While…Wend
Do…Loop
The For…Next looping construction repeats a sequence of programming statements a predetermined number of times. Consider the following For…Next VBScript example:
For iCounter = 1 To 10
MsgBox(“Loop step # “ & iCounter)
Next
The For…Next loop above will display 10 VBScript message boxes with the following messages:
Loop step # 1
Loop step # 2
…
…
Loop step # 10
You can use the Step keyword, to increase or decrease the loop step:
For iCounter = 1 To 5 Step 2
MsgBox(“# “ & iCounter)
Next
The For…Next loop above will display 3 VBScript message boxes with the following messages, because the iCounter increases with 2 on each loop step:
# 1
# 3
# 5
The For Each…Next statement repeats a sequence of programming statements for each element of an array or for each item in a collection.
Dim arrEmployees
arrEmployees = Array(“Peter”, “Stephen”, “Tracy”, “Jerry”)
For Each Item in arrEmployees
MsgBox(Item)
Next
The While…Wend statement repeats a sequence of programming statements while a condition is True.
While iCounter < 10
MsgBox(“Loop step # “ & iCounter)
iCounter = iCounter + 1
Wend
The Do…While…Loop statement repeats a sequence of programming statements while or until a condition is True.
Do While iCounter < 10
MsgBox(“Loop step # “ & iCounter)
iCounter = iCounter + 1
Loop
|