You can employ For...Next statements to run a block of statements a specific number of times. For loops, employ a counter variable whose value is increased or decreased with each repetition of the loop.
For instance, the following procedure causes a procedure called MyProc to execute 50 times. The For statement indicate the counter variable x and its begin and end values. The Next statement enhanced the counter variable by one.
Sub DoMyProc50Times() Dim x
For x = 1 To 50
MyProc
Next
End Sub
By using the Step keyword, you can increase or decrease the counter variable through the value you indicate. In the following instance, the counter variable j is enhanced by 2 each time the loop repeats. While the loop is finished, total is the sum of 2, 4, 6, 8, & 10.
Sub TwosTotal() Dim j, total
For j = 2 To 10 Step 2 total = total + j
Next
MsgBox "The total is " & total
End Sub
To reduce the counter variable, you employ a negative Step value. You have to specify an end value that is less than the start value. In the given example, the counter variable myNum is reduced by 2 each time the loop repeats. While the loop is finished, total is the sum of 16, 14, 12, 10, 8, 6, 4, & 2.
Sub NewTotal()
Dim myNum, total
For myNum = 16 To 2 Step -2 total = total + myNum
Next
MsgBox "The total is " & total
End Sub
You can exit any For...Next statement before the counter reaches its end value by using the Exit For statement. Since usually you want to exit only in certain situations, such as while an error take place, you must use the Exit For statement in the True statement block of an If...Then...Else statement. If condition is False, the loop runs usually. Or else perhaps you did not need to employ the loop in the first place.