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.
Written by Allen Wyatt (last updated January 13, 2023)
This tip applies to Excel 2007, 2010, 2013, and 2016
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:
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 writing a macro, you may want to fill a range of cells with different values. The easiest way to do this is to use ...
Discover MoreWant to step through the worksheets in a workbook, displaying them like a slideshow? The macros provided in this tip can ...
Discover MoreNeed to click on a cell and have it replaced with an "X"? Macros make it easy to do, as illustrated in this tip.
Discover MoreFREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."
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
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.
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.
FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."
Copyright © 2024 Sharon Parq Associates, Inc.
Comments