跳到循环vba中的下一次迭代

Käs*_*äse 27 vba loops

我正在尝试创建一个简单的条件循环,如果条件为真,它将进​​入下一次迭代.我到目前为止的代码是:

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
Run Code Online (Sandbox Code Playgroud)

我试过了GoTo NextIteration,但这会出现错误'Label not defined'.这可能有一个非常简单的解决方案,但非常感谢协助.谢谢.

B H*_*B H 33

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
Run Code Online (Sandbox Code Playgroud)

  • 它在OP发布的代码中。 (2认同)

Tan*_*ner 10

一旦满足条件,就什么都不做,否则做你需要的处理,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
Run Code Online (Sandbox Code Playgroud)

或者更改子句,使其仅在满足条件时才处理:

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
Run Code Online (Sandbox Code Playgroud)


小智 7

我使用转到

  For x= 1 to 20

       If something then goto continue

       skip this code

  Continue:

  Next x
Run Code Online (Sandbox Code Playgroud)


san*_*ica 5

当前的解决方案产生与您的 OP 相同的流程。它不使用标签,但这不是OP的要求。您只要求“一个简单的条件循环,如果条件为真,它将进​​入下一次迭代”,并且由于这更易于阅读,因此它可能是比使用 Label 更好的选择

你在for循环中想要的内容遵循模式

If (your condition) Then
    'Do something
End If
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您的条件是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
Run Code Online (Sandbox Code Playgroud)

PS:条件相当于(Return <> 0 Or Level <> 0)