The Visual Basic For Loop

The Visual Basic For loop takes on two separate forms. These are the For ... Next loop and the For Each loop.

The For ... Next Loop

The For ... Next loop sets a variable to a specified set of values, and for each value, runs the VBA code inside the loop. This is best explained by way of a simple example:
For i = 1 To 10
    Total = Total + iArray(i)
Next i
The above simple For ... Next loop sets the variable i to have the values 1, 2, 3, ..., 10, and for each of these values, runs through the VBA code inside the loop. Therefore, in the above example, the loop adds each of the entries of the array 'iArray' to the variable, 'Total'.
In the above example, no step size is specified, so the loop uses the default step size of 1, when looping from 1 to 10. However, you may sometimes want to step through a loop using different sized steps. This can be done using the Step keyword, as shown in the following simple example.
For d = 0 To 10 Step 0.1
    dTotal = dTotal + d
Next d
In the above For loop, because the step size is specified as 0.1, the value of d is set to the values 0.0, 0.1, 0.2, 0.3, ..., 9.9, 10.0 for each run through the VBA code inside the loop.
Although the previous examples all show increasing steps, you can also use negative step sizes, as is illustrated below:
For i = 10 To 1 Step -1
    iArray(i) = i
Next i
In this example, the step size is specified as -1, and so the loop sets the variable, i, to have the values, 10, 9, 8, ..., 1 in turn.

Popular posts from this blog

50 Excel VBA Oral Interview Questions