Using For Next to create a loop

A third pair of commands for creating loops in code is the For...Next block of statements. The syntax for a For...Next loop is shown here:

For counter = start To end [Step step] [statements] [Exit For]

[statements] Next [counter]

where

1 counter is any name that you want to give to the variable that keeps track of passes through the loop.

1 start is a number that indicates where the loop should start counting.

1 end is a number that indicates when the loop should end.

1 step is optional and indicates how much to increment or decrement counter with each pass through the loop. If omitted, counter increments by 1 with each pass through the loop.

i statements are any number of VBA statements that execute with each pass through the loop.

You can see many For...Next examples throughout this book. For now, when you're looking at existing code and see a For...Next pair of statements, realize that the statements inside that loop are executed repeatedly, as illustrated in Figure 4-7.

Code execution

Figure 4-7:

Statements inside this For...

Next loop are executed repeatedly.

Any VBA statement or comment 'Any VBA statement or comment Any VBA statement or comment

'Start of a For.. .Next loop For counter = 1 To 100

Any VBA statement or comment Any VBA statement or comment Any VBA statement or comment

Next

Any VBA statement or comment Any VBA statement or comment Any VBA statement or comment

0 0

Post a comment