Controlled Loops

To create a controlled loop, you must use the For...Next loop structure. This loop structure requires a counter variable to keep track of the current loop iteration along with the specification of how many loops should be ran. The following example demonstrates a For loop that doubles a variable's value:

Value = 5

For i = 1 To Value

'this will run 5 times (1 to 5)
Value = Value + 1

Next i

MsgBox Str(Value)

Note that this loop runs forward, one step at a time.  This is the default behavior for For loops, although you can alter the step size or direction very easily.  

To change the step size, simply use the Step keyword as follows:

Value = 6

For i = 1 To Value Step 2

'this will run 3 times because it steps by 2 now instead of 1
Value = Value + 1

Next i

To change the direction, first set the beginning of the loop to the larger value and then set the target (the value for the counter variable to reach) to the lower value, and then set the step to a negative value to force the loop to run backwards. The following example demonstrates this:

Value = 5

For i = value To 1 Step -1

'this will run 5 times (5 to 1) going backwards by 1
Value = Value + 1

Next i

MsgBox Str(Value)