VBA Do Until Loop
The Do Until
loop in VBA is a control flow statement that repeatedly executes a block of code until a specified condition becomes True
. It’s similar to the Do While
loop, but the logic is reversed.
Explanation:
condition
.condition
is False
, the code within the loop is executed.Exit Do
: You can use the Exit Do
statement within the loop to exit the loop prematurely if a certain condition is met.condition
is checked again.condition
is still False
, the code within the loop is executed again, and this process repeats.condition
becomes True
. Once the condition
becomes True
, the loop terminates, and the program continues to the next statement after the Loop
keyword.Syntax:
Do Until condition
[statements]
[Exit Do]
[statements]
Loop
Example
Sub CountToTen()
Dim counter As Integer
counter = 1
Do Until counter > 10
MsgBox counter
counter = counter + 1
Loop
End Sub
Above example:
counter
variable is initialized to 1.Do While
loop checks if counter
is less than or equal to 10.counter
is less than or equal to 10, the MsgBox
displays the current value of counter
, and then counter
is incremented by 1.counter
exceeds 10.Example with Exit Do
Sub FindNumber()
Dim i As Integer
i = 1
Do While i <= 10
If i = 5 Then
Exit Do
End If
MsgBox i
i = i + 1
Loop
End Sub
This code will display the numbers 1, 2, 3, and 4 in separate message boxes. When i
reaches 5, the Exit Do
statement will be executed, and the loop will terminate.
Key Points:
Do While
loop is useful when you need to execute a block of code repeatedly as long as a certain condition is met.Exit Do
statement can be used to exit the loop prematurely under specific conditions.False
.