Purpose
Executes a group of commands for each increment of a counter.
Syntax
For Counter = Start To End
Subcommands
Next
For Counter = Start To End
Commands
Next Counter
For Counter = Start To End Step Increment
Subcommands
Next
For Counter = Start To End
Subcommands
Condition
Exit For
Subcommands
Next
Each time a For...Next loop is iterated, the counter is incremented. You specify start and end values to indicate the initial and final values of the loop counter.
The default increment is 1; however, you can specify a different increment by adding the Step keyword. The increment can be any valid number.
If the increment is negative, the counter will count backwards from start to end. This is the only case where start is greater than end. You can also stop loop processing prematurely if a condition is met by using Exit.
Example
Dim i As Integer
For i = 1 to 10
If i > 5 Then
Exit For 'This will break the loop prematurely.'
End If
Print "Counting:", i
Next i
Next i
|