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.
by Allen Wyatt
(last updated May 20, 2019)
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, 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.
Save Time and Supercharge Excel! Automate virtually any routine task and save yourself hours, days, maybe even weeks. Then, learn how to make Excel do things you thought were simply impossible! Mastering advanced Excel macros has never been easier. Check out Excel 2010 VBA and Macros today!
When developing macros, you can create subroutines. This is a great way to reuse common code and make your programming ...Discover More
If you need to exit a macro before it is finished running, you can do it using a brute force method, or you can build in ...Discover More
Perhaps the most common way of communicating with programs is through the use of dialog boxes. We expect dialog boxes to ...Discover More
FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."
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.