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.
Learn more about Allen...
Please Note: This article is written for users of the following Microsoft Excel versions: 97, 2000, 2002, and 2003. If you are using a later version (Excel 2007 or later), this tip may not work for you. For a version of this tip written specifically for later versions of Excel, click here: Exiting a For ... Next Loop Early.
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 (2260) applies to Microsoft Excel 97, 2000, 2002, and 2003. You can find a version of this tip for the ribbon interface of Excel (Excel 2007 and later) here: Exiting a For ... Next Loop Early.
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!