如果满足语句,则在2个嵌套循环中断开内部循环

时间:2017-07-03 12:31:48

标签: vba excel-vba loops for-loop excel

我已经编写了以下代码我想打破m的循环,但是如果(if)语句返回true则想继续循环i

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

我希望外循环继续,但如果最后一个if语句变为真,则内循环中断

问题出在以下表达式

exit for
next i

1 个答案:

答案 0 :(得分:2)

如果您的退出条件为真,请检查正确的地方。 退出内循环应该在内循环中发生。

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

在你的情况下:

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

您也可以阅读how to avoid select