Exiting a nested for cycle

Lavina

Board Regular
Joined
Dec 18, 2018
Messages
75
Hello guys,

I sometimes have for loops nested in for loops, but once i find my answer id like all of the loops to exit, not just the current one. My current code looks like:
Code:
For Each item1 In fulllist1
    For Each item2 In fullList2
        If item2.Text = "hit" Then
            done = True
            Exit For
        End If
    Next
    If done Then Exit For
Next
Is there a better approach to do it?
 

Some videos you may like

Excel Facts

What is the fastest way to copy a formula?
If A2:A50000 contain data. Enter a formula in B2. Select B2. Double-click the Fill Handle and Excel will shoot the formula down to B50000.

offthelip

Well-known Member
Joined
Dec 23, 2017
Messages
1,077
Office Version
2010
Platform
Windows
you can put them all in a subroutine and use exit sub, this is what I do for multiple loops. You do need to declare variables at the module level though!
 

Lavina

Board Regular
Joined
Dec 18, 2018
Messages
75
I try to use global's as the last last resort, but that could indeed work, nice idea thank you! :)
 

Norie

Well-known Member
Joined
Apr 28, 2004
Messages
75,463
Office Version
365
Platform
Windows
Are the 2 loops/list connected?
 

MoshiM

Active Member
Joined
Jan 31, 2018
Messages
304
Hello guys,

I sometimes have for loops nested in for loops, but once i find my answer id like all of the loops to exit, not just the current one. My current code looks like:
Code:
For Each item1 In fulllist1
    For Each item2 In fullList2
        If item2.Text = "hit" Then
            done = True
            Exit For
        End If
    Next
    If done Then Exit For
Next
Is there a better approach to do it?
Have you tried using goto ?
 

Lavina

Board Regular
Joined
Dec 18, 2018
Messages
75
Are the 2 loops/list connected?
Sorry not sure what you mean by that, but let's imagine i'm browsing through a 2d array that has random numbers inside and i want to exit as soon as even a single copy of the number i'm looking for is found
 

Eric Golf

Active Member
Joined
Dec 19, 2007
Messages
324
Hi,

Untested but could you set a boolean variable e.g. bExitLoop to False, then set it to True just before exiting the inner loop, then in outer loop check the value of bExitLoop and if True, exit the outer loop?

Hope this helps,

Eric
 

Fluff

MrExcel MVP, Moderator
Joined
Jun 12, 2014
Messages
35,824
Office Version
365
Platform
Windows
Whilst it's very much down to personal preference, I tend to do it the same way you have.
I avoid using GoTo wherever possible.
 

Lavina

Board Regular
Joined
Dec 18, 2018
Messages
75
Hey Eric, thats exactly what i have! But I'm afraid when expanding i will run into problems
 

Watch MrExcel Video

Forum statistics

Threads
1,089,857
Messages
5,410,810
Members
403,330
Latest member
roxmasters2020

This Week's Hot Topics

Top