我希望在满足内部条件时退出for循环。当if条件满足时,我如何退出for循环?我认为在if语句的末尾会有某种退出,但不知道这是如何工作的。

Dim i As Long
For i = 1 To 50
    Range("B" & i).Select
    If Range("B" & i).Value = "Artikel" Then
        Dim temp As Long
        temp = i
    End If
Next i
Range("A1:Z" & temp - 1).EntireRow.Delete Shift:=xlToLeft

要提前退出循环,可以使用exit For

If [condition]则退出For


另一种提前退出For循环的方法是改变循环计数器:

For i = 1 To 10
    If i = 5 Then i = 10
Next i

Debug.Print i   '11

For i = 1 To 10
    If i = 5 Then Exit For
Next i

Debug.Print i   '5

以下给出的第一个答案确实是i.m.o.的最佳实践:

if i = 0 then exit for

然而,这也是一种选择:

Sub some()

Count = 0
End_ = ThisWorkbook.Sheets(1).Range("B1047854").End(xlUp).Row

While Count < End_ And Not ThisWorkbook.Sheets(1).Range("B" & Count).Value = "Artikel"
    Count = Count + 1
    If ThisWorkbook.Sheets(1).Range("B" & Count).Value = "Artikel" Then
        ThisWorkbook.Sheets(1).Range("A1:Z" & Count - 1).EntireRow.Delete Shift:=xlToLeft
    End If
Wend

End Sub

If condition(在while循环内)然后goto(在循环外的某个标记)