Microsoft Office Tutorials and References
In Depth Information
The For...Next statement executes a block of statements a prespecified number of times. It is
written like this:
For index = start To stop Step step
Next index
n index is a numeric variable that serves as the loop counter.
n start and stop are the starting and ending values of index.
n step is the amount that index is incremented with each repetition of the loop. If you
omit the step value, the default increment of 1 is used.
When a For...Next loop is encountered, here’s what happens:
1. index is set to the value of start .
2. index is compared to stop .
3. If index is less than or equal to stop , the statements in the loop are executed. If not,
the loop terminates.
4. index is incremented by the value of step (or by 1 if step is not specified).
Return to step 2.
This For...Next loop sets the values of the array to 0, 4, 8, ... 200:
Dim NewArray(50) As Integer
Dim j As Integer
For j = 0 To 50
NewArray(j) = j * 4
Next j
Code inside the loop should never change the value of the counter variable.
It is possible to use a For...Next loop to count down by making step negative. When you do
this, start must be greater than stop , and the loop terminates when counter is less than stop .
In this example, the For...Next loop fills the elements of the array with the values 100, 99, ... 0.
Dim NewArray(100) As Integer
Dim j As Integer
For j = 100 To 0 Step -1
NewArray(j) = 100 - j
Next j
Search JabSto ::

Custom Search