Excel VBA - 退出循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9414969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Excel VBA - exit for loop
提问by CustomX
I would like to exit my for
loop when a condition inside is met. How could I exit my for
loop when the if
condition has been met? I think some kind of exit at the end of my if
statement, but don't know how that would work.
for
当满足内部条件时,我想退出循环。满足条件for
时如何退出循环if
?我认为在我的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
回答by Dan
To exit your loop early you can use Exit For
要尽早退出循环,您可以使用 Exit For
If [condition] Then Exit For
If [condition] Then Exit For
回答by paul bica
Another way to exit a For loop early is by changing the loop counter:
提前退出 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
回答by ko_00
The first answer given with the following is indeed i.m.o. best practice:
以下给出的第一个答案确实是imo最佳实践:
if i = 0 then exit for
However, this is also an option:
但是,这也是一种选择:
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