【问题标题】:Continue For loop继续循环
【发布时间】:2011-08-19 05:58:59
【问题描述】:

我有以下代码

For x = LBound(arr) To UBound(arr)

    sname = arr(x)  
    If instr(sname, "Configuration item") Then  
        '**(here i want to go to next x in loop and not complete the code below)**  

    '// other code to copy past and do various stuff

Next x  

所以我认为我可以简单地使用声明 Then Next x,但这会产生“no for statement declared”错误。

那么我可以在If instr(sname, "Configuration item") Then 之后添加什么以使其进入 x 的下一个值?

【问题讨论】:

  • 感谢人们纠正我的拼写错误,我知道我的拼写很烂,并且很感激人们花时间帮助我。干杯

标签: vba loops for-loop next


【解决方案1】:

多年后 :D 我用一个“选择”语句作为一个简单的例子:

  For Each zThisRow In zRowRange
    zRowNum = zThisRow.Row
    Select Case zRowNum
      Case 1 '- Skip header row and any other rows to skip -----
             '- no need to put anything here -----

      Case Else '- Rows to process -----
             '- Process for stuff to do something here -----
    End Select
  Next zThisRow

您可以通过将每个“if”结果转换为一个值来使其变得尽可能复杂(也许有点过于复杂的代码会有助于解释 :D):

zSkip = 0
If 'condition1 = skip' Then zSkip = zSkip + 1
If 'condition2 = skip' Then zSkip = zSkip + 1
If 'condition3 = skip' Then zSkip = zSkip + 1
Select Case zRowNum
  Case 0 '- Stuff to do -----
  Case Else '- Stuff to skip -----
End Select

这只是一个建议;祝你圣诞快乐!

【讨论】:

    【解决方案2】:

    您可以通过简单的方式做到这一点,只需将 for 循环中使用的变量值更改为示例中所示的结束值

    Sub TEST_ONLY()
        For i = 1 To 10
            ActiveSheet.Cells(i, 1).Value = i
            If i = 5 Then
                i = 10
            End If
        Next i
    End Sub
    

    【讨论】:

      【解决方案3】:

      对于不使用“DO”的情况:这是我对带有嵌套 If 条件语句的 FOR EACH 的解决方案:

      For Each line In lines
          If <1st condition> Then
              <code if 1st condition>
              If <2nd condition> Then
                  If <3rd condition> Then
                      GoTo ContinueForEach
                  Else
                      <code else 3rd condition>
                  End If
              Else
                  <code else 2nd condition>
              End If
          Else
              <code else 1st condition>
          End If
      ContinueForEach:
      Next
      

      【讨论】:

        【解决方案4】:

        这也可以使用布尔值来解决。

        For Each rngCol In rngAll.Columns
            doCol = False '<==== Resets to False at top of each column
            For Each cell In Selection
                If cell.row = 1 Then
                    If thisColumnShouldBeProcessed Then doCol = True
                End If
                If doCol Then
                    'Do what you want to do to each cell in this column
                End If
            Next cell
        Next rngCol
        

        例如,以下是完整的示例:
        (1) 识别工作表上已使用单元格的范围
        (2) 循环遍历每一列
        (3) IF 列标题是可接受的标题,循环遍历列中的所有单元格

        Sub HowToSkipForLoopIfConditionNotMet()
            Dim rngCol, rngAll, cell As Range, cnt As Long, doCol, cellValType As Boolean
            Set rngAll = Range("A1").CurrentRegion
            'MsgBox R.Address(0, 0), , "All data"
            cnt = 0
            For Each rngCol In rngAll.Columns
                rngCol.Select
                doCol = False
                For Each cell In Selection
                    If cell.row = 1 Then
                        If cell.Value = "AnAllowedColumnTitle" Then doCol = True
                    End If
                    If doCol Then '<============== THIS LINE ==========
                        cnt = cnt + 1
                        Debug.Print ("[" & cell.Value & "]" & " / " & cell.Address & " / " & cell.Column & " / " & cell.row)
                        If cnt > 5 Then End '<=== NOT NEEDED. Just prevents too much demo output.
                    End If
                Next cell
            Next rngCol
        End Sub
        

        注意:如果您没有立即捕捉到它,If docol Then 行是您倒置的 CONTINUE。也就是说,如果 doCol 仍然为 False,则脚本继续到下一个单元格并且不执行任何操作。

        当然不如正确的 continuenext for 语句那么快/高效,但最终结果与我所能得到的一样接近。

        【讨论】:

          【解决方案5】:

          您正在考虑像Java'sPython's 这样的continue 语句,但是VBA 没有这样的本机语句,并且您不能像那样使用VBA 的Next

          您可以使用GoTo 语句代替您尝试做的事情,但实际上,GoTo 应该保留用于替代方案是人为且不切实际的情况。

          在您使用单个“继续”条件的情况下,有一个非常简单、干净且可读的替代方案:

              If Not InStr(sname, "Configuration item") Then
                  '// other code to copy paste and do various stuff
              End If
          

          【讨论】:

          • 当您在整个循环中有多个条件时,这不太干净且可读性较差。随着代码的嵌套越来越深,它需要更多的顶部空间供编码人员尝试阅读它。出于这个原因,GoTo 在这里可能会更好,而 Arlen Beiler 的回答是另一个不错的解决方案。
          • 我同意,这些会是更好的答案——针对不同的问题。不是这个。
          • 听起来我们同意,对于那些寻找更通用方法来解决 VBA 缺乏“继续”声明的人来说,下面的替代答案具有优势。我的意图只是通过权衡一般情况下的权衡来加深讨论。
          • 我的工作规则是:“检查你的先决条件,如果它们失败了,然后保释” 方法的开始,或循环的开始,同样的交易。如果可以的话,我会使用 continue,但我会使用 Goto,因为它会停止嵌套级别。
          • 我不知道为什么这里的每个人都在关注“多层嵌套”,而问题显然只有一个?...
          【解决方案6】:

          您可以使用GoTo

          Do
          
              '... do stuff your loop will be doing
          
              ' skip to the end of the loop if necessary:
              If <condition-to-go-to-next-iteration> Then GoTo ContinueLoop 
          
              '... do other stuff if the condition is not met
          
          ContinueLoop:
          Loop
          

          【讨论】:

          【解决方案7】:

          很多年后...我喜欢这个:

          For x = LBound(arr) To UBound(arr): Do
          
              sname = arr(x)  
              If instr(sname, "Configuration item") Then Exit Do 
          
              '// other code to copy past and do various stuff
          
          Loop While False: Next x
          

          【讨论】:

          【解决方案8】:

          我有时会做一个双重循环:

          Do
          
              Do
          
                  If I_Don't_Want_to_Finish_This_Loop Then Exit Do
          
                  Exit Do
          
              Loop
          
          Loop Until Done
          

          这避免了“goto spaghetti”

          【讨论】:

          【解决方案9】:
          For i=1 To 10
              Do 
                  'Do everything in here and
          
                  If I_Dont_Want_Finish_This_Loop Then
                      Exit Do
                  End If 
          
                  'Of course, if I do want to finish it,
                  'I put more stuff here, and then...
          
              Loop While False 'quit after one loop
          Next i
          

          【讨论】:

          • 这看起来是摆脱使用 Goto 继续我见过的 For 循环的最巧妙方法。我想你也可以采用相同的方法在其他情况下避免 Goto,就此而言......
          • 好答案。 Alfredo Yong 的回答是同样的想法,但 Alfredo 的回答简洁明了,对我来说更具可读性。
          • 哇。女士们先生们,“Do Once or Exit Do to Continue”的成语。
          • 这类似于 goto,但破坏了 goto 固有的达到不可预测状态的能力。 - 仍然使代码更难阅读,特别是如果一个人想做的事情很多。 - 在我看来,如果条件的逻辑反转变得太复杂而难以阅读或理解,这很有用。
          【解决方案10】:

          晚了几年,但这里有另一种选择。

          For x = LBound(arr) To UBound(arr)
              sname = arr(x)  
              If InStr(sname, "Configuration item") Then  
                  'Do nothing here, which automatically go to the next iteration
              Else
                  'Code to perform the required action
              End If
          Next x
          

          【讨论】:

          • 是的,但如果它有多个 continue 条件,这是手头问题的标准选择,导致丑陋的嵌套
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-03-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多