跳到循环 vba 中的下一次迭代
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20681306/
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
Skip to next iteration in loop vba
提问by K?se
I am trying to create a simple conditional loop that will go to the next iteration if a condition is true. The code I have so far is:
我正在尝试创建一个简单的条件循环,如果条件为真,它将进入下一次迭代。我到目前为止的代码是:
For i = 2 To 24
Level = Cells(i, 4)
Return = Cells(i, 5)
If Return = 0 And Level = 0 Then
'Go to the next iteration
Else
End If
Next
I have tried GoTo NextIteration
, but this comes up with the error 'Label not defined'. This probably has a very simple solution, but assistance would be much appreciated.
Thanks.
我试过了GoTo NextIteration
,但这会出现错误“标签未定义”。这可能有一个非常简单的解决方案,但将不胜感激。谢谢。
回答by B H
For i = 2 To 24
Level = Cells(i, 4)
Return = Cells(i, 5)
If Return = 0 And Level = 0 Then GoTo NextIteration
'Go to the next iteration
Else
End If
' This is how you make a line label in VBA - Do not use keyword or
' integer and end it in colon
NextIteration:
Next
回答by Tanner
Just do nothing once the criteria is met, otherwise do the processing you require and the For
loop will go to the next item.
满足条件后什么都不做,否则进行所需的处理,For
循环将转到下一项。
For i = 2 To 24
Level = Cells(i, 4)
Return = Cells(i, 5)
If Return = 0 And Level = 0 Then
'Do nothing
Else
'Do something
End If
Next i
Or change the clause so it only processes if the conditions are met:
或者更改子句,使其仅在满足条件时才进行处理:
For i = 2 To 24
Level = Cells(i, 4)
Return = Cells(i, 5)
If Return <> 0 Or Level <> 0 Then
'Do something
End If
Next i
回答by Sam
I use Goto
我使用转到
For x= 1 to 20
If something then goto continue
skip this code
Continue:
Next x
回答by sancho.s ReinstateMonicaCellio
The present solution produces the same flow as your OP. It does not use Labels, but this was not a requirement of the OP. You only asked for "a simple conditional loop that will go to the next iteration if a condition is true", and since this is cleaner to read, it is likely a better option than that using a Label.
本解决方案产生与您的 OP 相同的流程。它不使用标签,但这不是 OP 的要求。您只要求“一个简单的条件循环,如果条件为真,它将进入下一次迭代”,并且由于这更易于阅读,因此它可能是比使用 Label 更好的选择。
What you want inside your for
loop follows the pattern
您在for
循环中想要的内容遵循模式
If (your condition) Then
'Do something
End If
In this case, your condition is Not(Return = 0 And Level = 0)
, so you would use
在这种情况下,您的条件是Not(Return = 0 And Level = 0)
,因此您将使用
For i = 2 To 24
Level = Cells(i, 4)
Return = Cells(i, 5)
If (Not(Return = 0 And Level = 0)) Then
'Do something
End If
Next i
PS: the condition is equivalent to (Return <> 0 Or Level <> 0)
PS:条件等价于 (Return <> 0 Or Level <> 0)