2017-07-03 144 views
0

我已經寫了下面的代碼我想打破m的循環,但是如果(if)語句返回true,我想繼續循環我如果語句滿足,則在2個嵌套循環中打破內循環

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 

我要外循環繼續,但如果語句變成真正的內環打破,如果最後

問題出在下面的表達式

exit for 
next i 

回答

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