Please Note: This article is written for users of the following Microsoft Excel versions: 2007, 2010, 2013, and 2016. If you are using an earlier version (Excel 2003 or earlier), this tip may not work for you. For a version of this tip written specifically for earlier versions of Excel, click here: Exiting a For ... Next Loop Early.

Exiting a For ... Next Loop Early

Written by Allen Wyatt (last updated January 13, 2023)
This tip applies to Excel 2007, 2010, 2013, and 2016


15

If you use For ... Next loops in your macro programming (who doesn't?), then you should know that they can take a great deal of time. You can minimize this by only checking what you need. For instance, consider the following code, which checks an array to see if a value exists. If it doesn't, then it adds the value to the end of the array. If it does, then the value is not added.

AddIt = False
For J = 1 to NumEntries
    If NumValues(J) = ToAdd Then AddIt = True
Next J
If AddIt Then
    NumEntries = NumEntries + 1
    NumValues(NumEntries) = ToAdd
End If

This works great, but if the array gets large, you can end up going through the For ... Next loop quite a few times. Now consider the following code, which accomplishes the same task, but dumps out of the For ... Next loop early if a match is detected.

AddIt = False
For J = 1 to NumEntries
    If NumValues(J) = ToAdd Then
        AddIt = True
        Exit For
    End If
Next J
If AddIt Then
    NumEntries = NumEntries + 1
    NumValues(NumEntries) = ToAdd
End If

Now if a match is found early on in the loop, all the rest of the iterations are skipped because the Exit For statement is encountered and the loop is basically exited right away. The result is a faster running macro.

Note:

If you would like to know how to use the macros described on this page (or on any other page on the ExcelTips sites), I've prepared a special page that includes helpful information. Click here to open that special page in a new browser tab.

ExcelTips is your source for cost-effective Microsoft Excel training. This tip (11335) applies to Microsoft Excel 2007, 2010, 2013, and 2016. You can find a version of this tip for the older menu interface of Excel here: Exiting a For ... Next Loop Early.

Author Bio

Allen Wyatt

With more than 50 non-fiction books and numerous magazine articles to his credit, Allen Wyatt is an internationally recognized author. He is president of Sharon Parq Associates, a computer and publishing services company. ...

MORE FROM ALLEN

The Case of the Disappearing MRU File List

If the MRU list has disappeared, follow this tip to reactivate the list in Word.

Discover More

ISO Week Numbers in Excel

Work in an industry that uses ISO standards when it comes to working with dates? You'll love the formula in this tip ...

Discover More

Specifying Location for a Message Box

When writing macros, you may want to position a message box at a specific location on the screen. This can't be done in ...

Discover More

Professional Development Guidance! Four world-class developers offer start-to-finish guidance for building powerful, robust, and secure applications with Excel. The authors show how to consistently make the right design decisions and make the most of Excel's powerful features. Check out Professional Excel Development today!

More ExcelTips (ribbon)

Pulling Apart Characters in a Long String

You can easily use formulas to pull apart text stored in a cell. For instance, if you need to pull individual characters ...

Discover More

DOS from Macros

Need to run a DOS command from within one of your macros? The answer is the Shell command, described in this tip.

Discover More

Understanding the If ... End If Structure

One of the most basic of programming structures is the conditional structure: If ... End If. This tip explains how this ...

Discover More
Subscribe

FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."

View most recent newsletter.

Comments

If you would like to add an image to your comment (not an avatar, but an image to help in making the point of your comment), include the characters [{fig}] (all 7 characters, in the sequence shown) in your comment text. You’ll be prompted to upload your image when you submit the comment. Maximum image size is 6Mpixels. Images larger than 600px wide or 1000px tall will be reduced. Up to three images may be included in a comment. All images are subject to review. Commenting privileges may be curtailed if inappropriate images are posted.

What is 2 + 5?

2023-01-19 04:40:27

Barry

"If they attack one personally, it means they have not a single political argument left." - Margaret Thatcher

I'll not be wasting any more time on this thread.


2023-01-18 10:23:08

J. Woolley

bombastic: writing that is given exaggerated importance by artificial or empty means; high-sounding but with little meaning; inflated.

All code with Exit or GoTo is bad; therefore, Exit and GoTo should be abolished.


2023-01-17 05:43:43

Barry

@J.Woolley
If you have had to maintain/modify some badly written code, then I don't think you'd have levelled such an accusation

@Dave
I would contend that it's no more difficult or time consuming to write good code than bad code - especially if you take future Maintenance time into account.


2023-01-16 11:07:32

J. Woolley

@Barry
You could be right, but your comment is bombastic. An example might help. Here is one:

    AddIt = True
    j = 1
    Do Until j > NumEntries Or Not AddIt
        If NumValues(j) = ToAdd Then
            AddIt = False
        Else
            j = j + 1
        End If
    Loop
    If AddIt Then
        NumEntries = NumEntries + 1
        NumValues(NumEntries) = ToAdd
    End If


2023-01-16 11:02:43

Dave Bonin

Back in about 1981 in a computing course, Dr. Brookshear explained that the issue with GOTO statements was the lack of COME FROM statements. Yeah, there's some truth there.

I've programmed with GOTO and EXIT LOOP type statements and I've done some tortuous programming to avoid them. I eventually migrated to using what's simplest in each case and document it clearly. Why? Because I was paid to produce code that worked, not code that was academically pure and elegant.

I appreciate the apparent simplicity of DO...UNTIL and DO...WHILE, but neither works well in all situations.


2023-01-16 05:10:37

Barry

Using Exit Do is as bad as using Exit For, both are bad programming practice the use of which results in forming bad programming habits. They both should be abolished along with GoTo.

The example in this article is quiet simplistic and doesn't pose any major issues, but in more omplex situations it can lead to problems as I've outlined in my earlier post.


2023-01-15 15:48:56

J. Woolley

Incorporating comments by Doug and JMJ to add a NEW value to the end of an array using For...Next:

    AddIt = True
    For j = 1 To NumEntries
        If NumValues(j) = ToAdd Then
            AddIt = False
            Exit For
        End If
    Next j
    If AddIt Then
        NumEntries = NumEntries + 1
        NumValues(NumEntries) = ToAdd
    End If

Incorporating Barry's comment using Do...Loop:

    AddIt = True
    j = 1
    Do Until j > NumEntries
        If NumValues(j) = ToAdd Then
            AddIt = False
            Exit Do
        End If
        j = j + 1
    Loop
    If AddIt Then
        NumEntries = NumEntries + 1
        NumValues(NumEntries) = ToAdd
    End If

Do...Loop might be preferable in general, but it doesn't make much difference for this example. Personally, I find For...Next easier to read. Here is an alternate For...Next loop:

    For j = 1 To NumEntries
        AddIt = (NumValues(j) <> ToAdd)
        If Not AddIt Then Exit For
    Next j
    If AddIt Then
        NumEntries = NumEntries + 1
        NumValues(NumEntries) = ToAdd
    End If

And here is a more efficient version:

    For j = 1 To NumEntries
        If NumValues(j) = ToAdd Then Exit For
    Next j
    If j > NumEntries Then
        NumEntries = NumEntries + 1
        NumValues(NumEntries) = ToAdd
    End If

Here is another method using Collection, which is included in VBA:

    Dim NumValues As New Collection
    On Error Resume Next
        NumValues.Add ToAdd, CStr(ToAdd)
    On Error GoTo 0
    NumEntries = NumValues.Count

In this case, ToAdd must be a data type that can be converted to String (as key). If ToAdd is already in NumValues, attempts to add it will be ignored.
Here is another method using Dictionary with late binding:

    Dim NumValues As Object
    Set NumValues = CreateObject("Scripting.Dictionary")
    If Not NumValues.Exists(ToAdd) Then NumValues.Add ToAdd, ToAdd
    NumEntries = NumValues.Count

In this case, ToAdd can be anything except an array; notice ToAdd is both key and value. For early binding, add Microsoft Scripting Runtime to the VBAProject with Tools > References, then use this:

    Dim NumValues As New Dictionary
    If Not NumValues.Exists(ToAdd) Then NumValues.Add ToAdd, ToAdd
    NumEntries = NumValues.Count

Here is another method using ArrayList with late binding:

    Dim NumValues As Object
    Set NumValues = CreateObject("System.Collections.ArrayList")
    If Not NumValues.Contains(ToAdd) Then NumValues.Add ToAdd
    NumEntries = NumValues.Count

In this case, ToAdd can be anything including an array (single-dimension); however, if ToAdd is an array the If...Contains logic requires further consideration. For early binding, add mscorlib.dll to the VBAProject with Tools > References, then use this:

    Dim NumValues As ArrayList
    If Not NumValues.Contains(ToAdd) Then NumValues.Add ToAdd
    NumEntries = NumValues.Count

The "System.Collections.SortedList" object is also in mscorlib.dll.


2023-01-15 11:51:25

J. Woolley

@Dave Bonin
VBA does include an optional "Exit For" in the "For Each...Next" statement:
https://learn.microsoft.com/en-us/office/vba/language/reference/statements


2023-01-14 13:43:36

Al

@Elliot,
See comments by Doug and JMJ.


2023-01-14 04:34:56

Barry

Early exit of a For...Next or For...Each loop is not good programming practice. For...Next & For....Each are structures for loop through a set number of times. This is because in many cases only part of the code in the loop may be executed when the early exit occurs, this can lead to code maintenance issues in the future.
If you want to be able exit early then the preferable structures are Do...Until....Loop or the Do...Loop....Until structures.which only exit either at the beginning or end of a loop.


2023-01-13 18:54:22

Elliot

I am confused. Both macro versions appear to me to add a value to the array if, and only if, a match is found in the array. I.e. when a match is found Addit = True and If AddIt (= True) Then the value is added to the end of the array.


2023-01-13 13:50:05

Dave Bonin

I always found it odd that Microsoft didn't include an "Exit For" statement in the "For Each <item> in <collection>" loop


2019-05-21 13:24:56

JMJ

Yes, Doug is right: the test is reversed!


2014-12-01 07:21:49

Doug

Just a note to say that the Addit conditions are reversed in the code. It should be initialized to TRUE and set to FALSE if the value is detected in the loop.


2014-12-01 07:12:18

balthamossa2b

While it's not a good programming practice, I prefer going in and out of loops by using GoTo.

It's useful when you have a "loop of loops", or:

For i = 1 to n
For j = 1 to m
[stuff]
If (whatever) Then GoTo skiploop
Next j

For j = 1 to o
[otherstuff]
If (whatever) Then GoTo skiploop
Next j
skiploop:
Next i



The proper way to do this would be with embedded Ifs or with Booleans used as checks (as in this tip's example), but it's usually too bothersome.

And for big loops it can add too many extra operations that have an effect in the execution time (I'm thinking bruteforcing Project Euler-like stuff; in small loops of, say, <10k iterations you won't see the effect).

Yay for laziness.



This Site

Got a version of Excel that uses the ribbon interface (Excel 2007 or later)? This site is for you! If you use an earlier version of Excel, visit our ExcelTips site focusing on the menu interface.

Newest Tips
Subscribe

FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."

(Your e-mail address is not shared with anyone, ever.)

View the most recent newsletter.