Loop Statements (for, while, repeat) |
Top Previous Next |
For statement
The For statement can be used to repeatedly execute code. It allows to iterate from low to high bounds with specified step, or even in reverse order with negative step. If the Step clause is omit, then the default step is 1.
For i = 0 To 10 MsgBox(i) Next
For i = 0 To 10 Step 2 MsgBox(i) Next
For i = 10 To 0 Step -1 MsgBox(i) Next Do/Loop statement
The Do/Loop statement is a conditional loop statement. The statement supports While or Until conditions; and these conditions can be placed either: at the top or at the bottom of the statement. If the condition is placed at the top of the statement, then its checked before each execution (thus, even before first execution) of the loop child statements:
Dim i = 1 Do While i < 10 MsgBox(i) i = i * 2 Loop
Dim i = 1 Do Until i >= 10 MsgBox(i) i = i * 2 Loop If the condition is placed at the bottom of the statement, then its checked after each execution (thus, only after first execution) of the loop child statements:
Dim i = 1 Do MsgBox(i) i = i * 2 Loop While i < 10
Dim i = 1 Do MsgBox(i) i = i * 2 Loop Until i >= 10
Exit For/Do statement
The Exit For or Exit Do statements can be used to break loop execution. Using Exit For or Exit Do statements outside of the corresponding loop is a syntax error.
Dim i = 1 Do While i < 100 If i = 15 Then Exit Do End If i = F(i) Loop
Dim sum = 0 For i = 0 To 10 sum = sum + i If sum > 15 Then Exit For End If Next
The Exit For or Exit Do statements always works with innermost loop:
For i = 0 To 10 'outer If i = 5 Then Exit For 'Break outer loop. End If
For j = 0 To 10 'inner If j = 5 Then Exit For 'Break inner loop. End If Next Next |