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

时间:2013-12-19 12:02:37

标签: 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

我已经尝试了GoTo NextIteration,但这会出现错误“标签未定义”。这可能有一个非常简单的解决方案,但非常感谢协助。 感谢。

8 个答案:

答案 0 :(得分:28)

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

答案 1 :(得分:9)

符合条件后什么都不做,否则进行所需的处理,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

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

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

答案 2 :(得分:3)

我使用Goto

  For x= 1 to 20

       If something then goto continue

       skip this code

  Continue:

  Next x

答案 3 :(得分:1)

本解决方案产生的流量与OP相同。 它不使用标签,但这不是OP的要求。您只询问“如果条件为真,将进入下一次迭代的简单条件循环”,并且由于读取起来比较清晰,它可能是比使用Label 更好的选择。

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

If (your condition) Then
    'Do something
End If

在这种情况下,您的条件为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:条件相当于(Return <> 0 Or Level <> 0)

答案 4 :(得分:0)

您可以通过使用嵌套的 continue 来使用一种 Do ... Loop While False

'This sample will output 1 and 3 only

Dim i As Integer

For i = 1 To 3: Do

    If i = 2 Then Exit Do 'Exit Do is the Continue

    Debug.Print i

Loop While False: Next i

答案 5 :(得分:-1)

最简单的方法是使用goto。下面是将Nexti用作goto标签的代码

   For i = 2 To 24
        Level = Cells(i, 4)
        Return = Cells(i, 5)

        If Return = 0 And Level = 0 Then
            GoTo Nexti
        Else
        End If
    Nexti:
Next

答案 6 :(得分:-2)

For i = 2 To 24
Level = Cells(i, 4)
Return = Cells(i, 5)

If Return = 0 And Level = 0 Then
i = 24
Else
End If

只是让它跳到循环的末尾?

答案 7 :(得分:-2)

我发现从循环内任何点(Pascal中Continue运算符的类似物)进行下一次迭代的最简单方法是使用附加的单遍循环和运算符Exit For

'Main loop
For i = 2 To 24
    'Additional single pass loop
    For t = 1 To 1
        Level = Cells(i, 4)
        Return = Cells(i, 5)

        If Return = 0 And Level = 0 Then
            'Go to the next iteration
            Exit For 
        Else
        End If
    Next
Next