VBA Exit For

Associated Files Download Links

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

When the execution of the code comes to Exit For, it will exit a For loop and continue with the first line after the loop.

If you want to learn how to exit a Do loop, click on this link: VBA Exit Loop

 

Exit a For Loop When a Condition is Met

You will see on the example how to exit a For 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 5, we want to exit the loop and return a message box. Here is the code:

 

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

After that we check if the value of i is equal to 5, using the If command. If the value is 5, we exit the For loop and go to the first line after the loop:

If the condition is not met, the following statement increases i by 1 and enters in the For loop again:

The first line of the code which will be executed after exiting the For 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 5 times. In the 5th iteration, the value of the variable i becomes 5 and the code enters in the If body. Now the body of the For loop is exited. After that, the MsgBox pop-ups with the value of i:

vba exit for

Image 1. Exit For Loop example

 

You may also like some of this related content...

In VBA, you can exit a Do loop using the Exit Do command. Exit Do
In VBA, you can loop through a range of cells, applying actions to each cell
You can perform logic on, or return individual characters from a string in VBA by
Macros applied to an entire workbook can be handy for extracting data from multiple sheets
Ads