VBA Exit For

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

Exit For

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:

Dim i As Integer

   For i = 1 To 10     
        If i = 5 Then
            Exit For
        End If
    Next i

MsgBox "The value is " & i

 

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

For i = 1 To 10

Next i

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 i = 5 Then

    Exit For

End If

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

Next i

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

MsgBox "The value is " & 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