lang • for

FOR

FOR Variable = Expression { TO | DOWNTO } Expression [ STEP Expression ] ... NEXT

Repeats a loop while incrementing or decrementing a variable.

The loop variable must be:

If DOWNTO is used instead of TO, then the increment step is reversed.

If the initial expression is higher than the final expression (for positive STEP values), or if the initial expression is less than the final expression (for negative ones) the loop will not be executed at all.

Loop variable declaration

Since 3.12

Loop variable can be declared directly by following that syntax:

FOR Variable AS Datatype = Expression { TO | DOWNTO } Expression [ STEP Expression ] ... NEXT

The scope of the loop variable is still function-wide. In other words, declaring the loop variable that way has the same effect as declaring it at the beginning of the function, except that you can only use it after the declaration.

You can declare the same loop variable as much time as you want provided that the declaration is the same.

Examples

Dim iCount As Integer

For iCount = 1 To 20 Step 3
  Print iCount;;
Next
1 4 7 10 13 16 19
For iCount = 10 DownTo 1
  Print iCount;;
Next
10 9 8 7 6 5 4 3 2 1
For iCount = 10 DownTo 1 Step 3
  Print iCount;;
Next
10 7 4 1
For I As Integer = 1 To 10
  Print I;;
Next
1 2 3 4 5 6 7 8 9 10

See also