VBA Exit Loop
Written by
Reviewed by
In VBA, you can exit a Do loop using the Exit Do command.
Exit Do
When the execution of code comes to Exit Do, the code will exit the Do loop and continue with the first line after the loop.
If you want to learn how to exit a For loop, click on this link: VBA Exit For
Exit a Loop When a Condition is Met
You will see in the example below how to exit a Do loop when a certain condition is met. We will loop and increment the value of the variable i by 1 in every iteration. When it comes to 6, we want to exit the loop and return a message box. Here is the code:
Dim i As Integer
Do While i < 10
i = i + 1
If i = 6 Then
Exit Do
End If
Loop
MsgBox "The value is " & i
First, we enter the Do Loop if the value of i is less than 10:
Do While i < 10
Loop
In the body of the loop, we increment the value of i by 1:
i = i + 1
After that we check if the value of i is equal to 6, using the If command. If the value is 6, we exit the Do loop and go to the first line after the loop:
If i = 6 Then
Exit Do
End If
The first line of the code which will be executed after exiting the Do loop is the message box with the value of i:
MsgBox "The value is " & i
If you execute this code in Debug Mode, you will see that it will go through the loop 6 times. In the 6th iteration, the value of the variable i becomes 6 and the code enters in the If body. Now the body of the Do loop is exited. After that, the MsgBox pop-ups with the value of i:
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro - A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!Learn More!