Search code examples
vbafor-loopif-statementnested-loops

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.


Solution

  • 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