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.

The TO or DOWNTO Expression is evaluated once at the beginning of the loop, not after each iteration. So the following loop will halt:

For i As Integer = 0 To i + 1
  Print i
Next
Print "Finish!"
0
1
Finish!

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 As Integer = 10 DOWNTO 1
  PRINT iCount;;
NEXT
10 9 8 7 6 5 4 3 2 1

FOR iCount As Integer = 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