Repeating a Loop While a Condition Is True

Use the While keyword to check a condition in a Do...Loop statement. You can check the condition before you enter the loop (as shown in the first example following this paragraph), or you can check it after the loop has run at least once (as shown in the second example).

The first loop made 10 repetitions.

The second loop made 1 repetitions.

Repeating a Statement Until a Condition Becomes True

You can use the Until keyword in two ways to check a condition in a Do...Loop statement. You can check the condition before you enter the loop (as shown in the first example following this paragraph), or you can check it after the loop has run at least once (as shown in the second example). As long as the condition is False, the looping occurs.

The first loop made 10 repetitions.

The second loop made 9 repetitions.

Exiting a Do ... Loop Statement from Inside the Loop

You can exit a Do ... Loop by using the Exit Do statement. You usually want to exit when you have accomplished the task the loop is performing or in certain situations to avoid an endless loop.

In the following example, myNum is assigned a value that creates an endless loop. The If...Then...Else statement checks for this condition, preventing the endless repetition.

The loop made 1 repetitions.