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

Quickly Selecting Cells

Need to quickly select a range of cells? Perhaps the easiest way is to use both the mouse and the keyboard together, as ...

Discover More

Finding Rows with Values in Two Columns

When you use Excel to input and store information, you need to be concerned with whether the information meets your ...

Discover More

A Shortcut for Switching Focus

While not technically an Excel-only tip, the shortcuts described in this tip will help you switch focus from your ...

Discover More

Comprehensive VBA Guide Visual Basic for Applications (VBA) is the language used for writing macros in all Office programs. This complete guide shows both professionals and novices how to master VBA in order to customize the entire Office suite for their needs. Check out Mastering VBA for Office 2010 today!

More ExcelTips (ribbon)

Macro Runs Slowly, but Steps Quickly

When you have a macro that processes a huge amount of data, it can seem like it takes forever to finish up. These ...

Discover More

Replacing and Converting in a Macro

When you use a macro to process data you always run the risk of making that data unusable by Excel. This is especially ...

Discover More

Converting Numbers Into Words

Write out a check and you need to include the digits for the amount of the check and the value of the check written out ...

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 eight minus 3?

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.