For next
For...Next
Repeats a block of statements a fixed number of times, using a counter variable that increments (or decrements) after each iteration.
Syntax
For counter = start To end [Step stepValue]
[statements]
[Exit For]
Next [counter]
Parameters
- counter: A numeric variable used as the loop control variable.
- start: The initial value of
counter. - end: The final value of
counter. - stepValue: The amount added to
counterafter each iteration. Defaults to1. - statements: One or more statements to execute inside the loop.
Remarks
- If
stepValueis positive, the loop runs whilecounter <= end. - If
stepValueis negative, the loop runs whilecounter >= end. Exit Forexits the loop immediately from any point inside it.- Including the counter name after
Nextis optional but improves readability.
Examples
Dim i As Integer
For i = 1 To 5
Print i
Next i
' Output: 1 2 3 4 5
' Count down using a negative Step
Dim i As Integer
For i = 10 To 1 Step -2
Print i
Next i
' Output: 10 8 6 4 2