See Also Example
Repeats a block of statements while a condition is true or until a condition becomes true.
Syntax 1
Do [{ While | Until} condition]
[statementblock]
[Exit Do]
[statementblock]
Loop
Syntax 2
Do
[statementblock]
[Exit Do]
[statementblock]
Loop [{ While | Until} condition]
Remarks
The Do...Loop statement has these parts:
Part Description
Do Must be the first statement in a Do...Loop control structure.
While Indicates that the loop is executed while condition is true.
Until Indicates that the loop is executed until condition is true.
condition Numeric or string expression
statementblock Program lines between the Do and Loop statements that are repeated while or until condition is true.
Exit Do Only used within a Do...Loop control structure to provide an alternate way to exit a Do...Loop. Any number of Exit Do statements may be placed anywhere in the Do...Loop. Often used with the evaluation of some condition (for example, If...Then), Exit Do transfers control to the statement immediately following the Loop.
Loop Ends a Do...Loop.
When Do...Loop statements are nested, control is transferred to the Do...Loop that is one nested level above the loop in which the Exit Do occurs.
Exit Statement
While...Wend Statement
The example creates an infinite Do...Loop that can be exited only if the user enters a number in a range. To try this example, paste the code into the Declarations section of a form. Then press F5 and click the form.
Sub Form_Click ()
Dim Reply ' Declare variable.
Do
Reply = InputBox("Enter a number greater than 1 and less than 9.")
If Reply > 1 And Reply < 9 Then ' Check range.
Exit Do ' Exit Do Loop.
End If
Loop
End Sub
Alternatively, the same thing can be accomplished by incorporating the range test in the Do...Loop as follows:
Sub Form_Click ()
Dim Reply ' Declare variable.
Do
Reply = InputBox("Enter a number greater than 1 and less than 9.")
Loop Until Reply > 1 And Reply < 9
End Sub