Using Do...Loop Statements
You can use Do...Loop statements to run a block of statements an indefinite number of times. The statements are repeated either while a condition is True or until a condition becomes True.
Repeating Statements While a Condition is True
There are two ways to use the Whilekeyword to check a condition in a Do...Loop statement. You can check the condition before you enter the loop , or you can check it after the loop has run at least once.
In the following
|
procedure, you check the condition before you enter the loop. If
|
is set to 9 instead of 20, the statements inside the loop will never run. In the
|
procedure, the statements inside the loop run only once before the condition becomes False.
|
Repeating Statements Until a Condition Becomes True
There are two ways to use the Until keyword to check a condition in a Do...Loop statement. You can check the condition before you enter the loop (as shown in the
|
procedure), or you can check it after the loop has run at least once (as shown in the
|
procedure). Looping continues while the condition remains False.
|
Exiting a Do...Loop Statement from Inside the Loop
You can exit a Do...Loop using the Exit Do statement. For example, to exit an endless loop, use the Exit Do statement in the True statement block of either an If...Then...Else statement or a Select Case statement. If the condition is False, the loop will run as usual.
In the following example,
|
is assigned a value that creates an endless loop. The If...Then...Else statement checks for this condition, and then exits, preventing endless looping.
|
Note |
---|
To stop an endless loop, press ESC or CTRL+BREAK. |