VBA Exit Loop

Associated Files Download Links

In VBA, you can exit a Do loop using the Exit Do command.

When the execution of the code comes to Exit Do, it will exit a 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 on the example 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:


First, we enter the Do Loop if the value of i is less than 10:

In the body of the loop, we increment the value of i by 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:

The first line of the code which will be executed after exiting the Do loop is the message box with the value of i:


If you execute this code in the 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 exit loop

Image 1. Exit Do Loop example