【问题标题】:Skip to next iteration in loop vba跳到循环 vba 中的下一次迭代
【发布时间】:2014-01-07 23:57:48
【问题描述】:

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

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,但出现错误“标签未定义”。这可能有一个非常简单的解决方案,但非常感谢您的帮助。 谢谢。

【问题讨论】:

  • whats Level whats Return,你的电子表格是什么样子的
  • VbScript 中没有Continue。您将不得不玩 If-Else 以跳过任何迭代。浏览@AlexK 发布的链接。它有一些很好的建议。
  • 两个整数,如果这两个值都是 0,我正在尝试确保代码不会运行。
  • 没有人说过不应该使用Return...(你知道...它用于其他东西,如果用作变量可能会导致巨大的问题)跨度>

标签: excel vba loops


【解决方案1】:
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
    GoTo NextIteration
  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

【讨论】:

  • 为什么elseif 之后?我得到end if without if block
  • 它在 OP 发布的代码中。
  • 我明白了,IT 生活不是复制粘贴。
  • @timo:它可能不像我最初拥有的那样工作,所以我将实际执行的“GoTo”移动到评论下,就像大多数人习惯的那样。
【解决方案2】:

一旦满足条件就什么也不做,否则执行您需要的处理,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

【讨论】:

  • 不应该是 If Return 0 还是 Level 0 Then,所以与 If Return = 0 And Level = 0 Then 正好相反?
  • 第二个似乎有效,但我认为我需要一个 Or 而不是 And。我认为也需要一个 Else。
【解决方案3】:

我使用转到

  For x= 1 to 20

       If something then goto continue

       skip this code

  Continue:

  Next x

【讨论】:

  • 最简单(= 最佳)的解决方案(我赞成),但“跳过此代码”应改为“如果'某事'为真则跳过此代码”。
【解决方案4】:

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

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 &lt;&gt; 0 Or Level &lt;&gt; 0)

【讨论】:

    【解决方案5】:

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

    '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
    

    【讨论】:

      猜你喜欢
      • 2015-11-11
      • 1970-01-01
      • 1970-01-01
      • 2015-05-03
      • 1970-01-01
      • 2017-10-05
      • 1970-01-01
      • 2019-05-06
      相关资源
      最近更新 更多