0

I have written the following code I want to break the loop of m, but want to continue the loop of i if the (if) statement returns true

For i = 7 To lastrow
    For m = 33 To 37

        If IsNumeric(mmk.Sheets("FG").Cells(i, m)) = True Then
            quote(i, m) = mmk.Sheets("FG").Cells(i, m)
        End If

        If quote(i, m) <> Empty And quote(i, m) <> 0 And quote(i, m) > 0 Then
            row(i, m) = i
        End If

       row1(i) = row(i, m)

       If row1(i) <> Empty And row1(i) <> 0 And row1(i) > 0 Then
           mmk.Sheets("FG").Rows(row1(i)).Select
           Selection.Copy
           wrk.Activate
           wrk.Sheets("Nego").Activate

           With ActiveSheet
               last1 = .Cells(.Rows.Count, "A").End(xlUp).row
           End With

           wrk.Sheets("Nego").Cells(last1 + 1, 1).Select
           ActiveSheet.Paste
           Exit For
           Next i
        Else
           Next m
           Next i
        End If

I want the outer loop to continue but the inner loop to break if the last if statement turns true

the problem is in the following expression

exit for
next i
Community
  • 1
  • 1

1 Answers1

3

It's a matter of checking in the right place if your exit condition is true. Exiting the inner loop should happen within the inner loop.

Sub BreakInnerLoops()

Dim i As Integer
Dim j As Integer
Dim k As Integer

For i = 1 To 10
    For j = 1 To 10
        For k = 1 To 10
            Debug.Print i & " " & j & " " & k
            If k = 5 Then Exit For 'Exits k loop.
        Next k
        If j = 5 Then Exit For 'Exits j loop.
    Next j
    If i = 5 Then Exit For 'Exits i loop.
Next i

End Sub

In your case:

For i = 7 To lastrow 
    For m = 33 To 37
        'Some lines here.
        If row1(i) <> Empty And row1(i) <> 0 And row1(i) > 0 Then 'Exit condition and do stuff.
            mmk.Sheets("FG").Rows(row1(i)).Select
            Selection.Copy
            wrk.Activate
            wrk.Sheets("Nego").Activate
            With ActiveSheet
                last1 = .Cells(.Rows.Count, "A").End(xlUp).row
            End With
            wrk.Sheets("Nego").Cells(last1 + 1, 1).Select
            ActiveSheet.Paste
            Exit For
        End If
    Next m
Next i

Also you might want to read how to avoid select

Rik Sportel
  • 2,661
  • 1
  • 14
  • 24