简体   繁体   中英

VBA nested “for” and “if”

I am doing nested if within loops, which is basically:

1:  For i = 1 To n
    If condition1 Then
2:     For j = 1 To m
           If condition2 Then
3:            For k = 1 To p
                  If condition3 Then
                     statement1
                  End If
              Next k
           End If
        Next j
    End If
    Next i

After statement1 , I would like to Exit the loop 2 and 3 and go directly to 1 .

However if I use Exit For this will only exit 3 . If I put a line before 1 , and then use GoTo to refer to it, it will not work either because the program has to start with 1 .

you could use a helper Boolean variable to mark when to exit loop 2, as follows

Dim exitLoop2 As Boolean

For i = 1 To n
    If condition1 Then
        exitLoop2 = False ' set it to false at the beginning of any loop 2
        For j = 1 To m
            If condition2 Then
                For k = 1 To p
                    If condition3 Then
                        exitLoop2 = True ' this will make you exit loop 2 once out of loop 3
                        Exit For ' this will exit loop 3
                    'statement1
                    End If
                Next
            End If
            If exitLoop2 Then Exit For ' exit loop 2 if needed
        Next
    End If
Next

There is more elegant way. Wrap the code you need to exit from into dummy Do ... Loop Until True block, then use Exit Do for immediate exit.

For i = 1 To n
    Do
        If condition1 Then
           For j = 1 To m
               If condition2 Then
                  For k = 1 To p
                      If condition3 Then
                         statement1
                         Exit Do
                      End If
                  Next k
               End If
            Next j
        End If
    Loop Until True
Next i

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM