user95902
user95902

Reputation: 159

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.

Upvotes: 1

Views: 69

Answers (2)

omegastripes
omegastripes

Reputation: 12612

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

Upvotes: 1

DisplayName
DisplayName

Reputation: 13386

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

Upvotes: 2

Related Questions