Please Note: This article is written for users of the following Microsoft Excel versions: 2007 and 2010. 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

by Allen Wyatt
(last updated September 7, 2015)

2

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.

ExcelTips is your source for cost-effective Microsoft Excel training. This tip (11335) applies to Microsoft Excel 2007 and 2010. 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

Embedding TrueType Fonts

If you need to make sure that the fonts in your document can be used by another person or on a different system, you'll need ...

Discover More

Repeating Cell Contents

Want to repeat cell contents over and over again within a single cell? Excel provides two ways you can duplicate the content.

Discover More

Odd Page Numbers Disappearing

Page numbers in printed pages are often a necessary part of formatting a document. What do you do if your printed output ...

Discover More

Excel Smarts for Beginners! Featuring the friendly and trusted For Dummies style, this popular guide shows beginners how to get up and running with Excel while also helping more experienced users get comfortable with the newest features. Check out Excel 2013 For Dummies today!

More ExcelTips (ribbon)

Determining the Current Directory

When you use a macro to do file operations, it works (by default) within the current directory. If you want to know which ...

Discover More

Extracting Proper Words

If you've got a list of potential words, and you want to know which of those potential words are real, you'll appreciate the ...

Discover More

Conditionally Displaying a Message Box

You can, from within your macros, easily display a message box containing a message of your choice. If you want to display ...

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}] 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 four less than 9?

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.