VBA break is Available? How to Exit For Loop?

In programming languages, there is normally a break statement is available to exit a loop (For, While, Do While) while it is still not completed. There is no break statement in VBA.

What is break statement generally?

In programming languages, there is normally a break statement available to exit a loop (For loop, While, Do While) while it is still not completed.

There is no break keyword/statement in VBA.

Using the Exit For

In VBA, we use Exit For to get out of the for loop entirely.

We will show you simple as well as exiting for loop in the array below.

How to exit a for loop in VBA?

In this example,

  • we set a variable initial value to 1.
  • A for loop is used to iterate till value of variable i = 10
  • In each iteration, the value of i increases by 1.
  • We will concatenate the current value of i, and as for loop finishes, a MsgBox is displayed as shown below:

Normal for loop without breaking it:

Output:

VBA-for-loop-normal

Break the for loop by Exit For

The example below exits the For loop by using “Exit For” as the value of i reaches 5:

VBA code:

Output:

VBA-for-loop-exit

You can see, For loop till the value of i reached 5.

Exiting an array with For Each loop example

Similarly, you may exit the For..Each loop that we use with arrays or collections.

In the example below, we have a string array of four elements. As we reach the third item, we will check its value and exit the For..Each loop.

First, let us show how it works without Exit For:

The code:

Output:

VBA-for-each

Now, we will exit the For..Each loop as it encountered the array element “C++”. So, MsgBox should display only two languages:

Code with “Exit For”:

Result:

VBA-for-each-Exit