For...Next Loop
VBScript uses the For…Next structure for creating incremental loops. There are a few keyword variations that allow some flexibility in how the loop is executed.
Syntax:
For variable = intStart To intEnd [Step intIncrement]
' Code to be repeated
Next
A basic For…Next statement is used to repeat a section of code a definite number of times. The following code will count to 5 and print each number.
Exampel:
For x = 1 To 5
WScript.Echo x
Next
The For statement requires that you supply a counter variable such as “x.” You must also supply its starting and ending value. The Next statement will increment the counter variable and repeat the enclosed code until it is no longer within the specified range, resulting in an output like the following:
1
2
3
4
5
The For statement also accepts the Step keyword which can be used to change the increment value. You may supply a negative number to cause the counter to decrement. The following example will list all even numbers from 10 to 0.
Example:
For x = 10 To 0 Step -2
Wscript.Echo x
Next
Make sure that your starting value is less than your ending value when incrementing and greater than it when decrementing in order to prevent errors. The second output looks like this:
10
8
6
4
2
0
For Each…Next loop
Another variation of this loop is the For Each…Next loop. This Each keyword will iterate through each element in a dictionary object, array, or collection.
arrWords = Array("Red", "Green", "Blue", "Black", "White")
For Each strWord In arrWords
WScript.Echo strWord
Next
Using the For Each statement, we iterated through each element without having to specify the number explicitly. The first variable in this statement must be a reference to the array element followed by the In keyword and a variable representing the array. The resulting output makes this very evident.
Red
Green
Blue
Black
White
This same output can be generated using a simple For loop, however, the code is much more complex.
For i = 0 To UBound(arrWords)
strWord = arrWords(i)
Wscript.Echo strWord
Next
In this example, we had to programmatically determine the number of elements in the array and then make a reference to each of them. The For Each syntax is a much cleaner, quicker approach.