For...Next

The For…Next statements are used to repeat a group of instructions a specified number of times.

Syntax

For counter = start To end [ Step increment ]

          [statementblock]

          [ExitFor]

          [statementblock]

Next [counter [, counter][, ...]]

Remarks

The For...Next statement has these parts:

For

The For statement begins a For...Next loop control structure. For must appear before any other part of the structure.

Counter

The Counter is a numeric variable used as the loop counter. If the variable used is an index into an array, the index cannot be a variable (for example, Variable(1) can be used, but Variable(i) cannot).

Start

The Start parameter is the constant or variable to use for the initial value of counter.

To

The To statement separates the Start and End values.

End

The End parameter is the constant or variable to use for the final value of counter.

Step

The Step argument is used to indicate that the For…Next loop should increment the counter by a specific value each pass through the loop.

Increment

The Increment parameter is the amount the counter is changed each time through the loop. Increment can be a positive or negative value. If you do not use Step Increment, the counter is incremented by 1 each pass through the loop.

StatementBlock

The StatementBlock is the portion of the program that should be repeated until the loop is terminated. These instructions lie between the For and Next statements.

ExitFor

The ExitFor statement is used within a For...Next control structure to provide an alternate way to exit. Any number of ExitFor statements may be placed anywhere in the For...Next loop. This statement is often used with the evaluation of some condition (for example, If...Then). ExitFor transfers control to the statement immediately following the Next.

Next

The Next statement ends a For...Next loop. This statement cause the counter to increase by the Step Increment.

For...Next loops can be nested by placing one For...Next loop within another. Each loop should be given a unique variable name for its counter. If nesting is used, when the For…Next loop is exited, program control is transferred to the For…Next loop in which it was nested.