Do...Loop Statement
Description
Repeats a block of statements while a condition is True or until a condition becomes True.
Syntax
Do [{While | Until} condition]
[statements]
[Exit Do]
[statements]
Loop
Or, you can use this syntax:
Do
[statements]
[Exit Do]
[statements]
Loop [{While | Until} condition]
The Do Loop statement syntax has these parts
Part | Description |
|
condition | Optional. Numeric expression or string expression that is True or False. If condition is Null, condition is treated as False. |
statements | One or more statements that are repeated while, or until, condition is True. |
Remarks
Any number of Exit Do statements may be placed anywhere in the Do…Loop as an alternate way to exit a Do…Loop. Exit Do is often used after evaluating some condition, for example, If…Then, in which case the Exit Do statement transfers control to the statement immediately following the Loop.
When used within nested Do…Loop statements, Exit Do transfers control to the loop that is one nested level above the loop where Exit Do occurs.
See Also
Exit statement, For...Next statement, While...Wend statement.
Example
This example shows how Do...Loop statements can be used. The inner Do...Loop statement loops 10 times, sets the value of the flag to False, and exits prematurely using the Exit Do statement. The outer loop exits immediately upon checking the value of the flag.
Dim Check, Counter
Check = True: Counter = 0 ' Initialize variables.
Do ' Outer loop.
Do While Counter < 20 ' Inner loop.
Counter = Counter + 1 ' Increment Counter.
If Counter = 10 Then ' If condition is True.
Check = False ' Set value of flag to False.
Exit Do ' Exit inner loop.
End If
Loop
Loop Until Check = False ' Exit outer loop immediately.
Example (Microsoft Excel)
This example sorts the data in the first column on Sheet1 and then deletes any rows that contain duplicate data.
Worksheets("Sheet1").Range("A1").Sort _
key1:=Worksheets("Sheet1").Range("A1")
Set currentCell = Worksheets("Sheet1").Range("A1")
Do While Not IsEmpty(currentCell)
Set nextCell = currentCell.Offset(1, 0)
If nextCell.Value = currentCell.Value Then
currentCell.EntireRow.Delete
End If
Set currentCell = nextCell
Loop