VBA Do While Loop
The Do While
loop in VBA is a control flow statement that repeatedly executes a block of code as long as a specified condition remains True.
Explanation:
condition
.condition
is True
, 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 True
, the code within the loop is executed again, and this process repeats.condition
becomes False
. Once the condition
becomes False
, the loop terminates, and the program continues to the next statement after the Loop
keyword.Syntax:
Do While condition
[statements]
[Exit Do]
[statements]
Loop
Example
Sub CountToTen()
Dim counter As Integer
counter = 1
Do While 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
.