继续循环

Dev*_*WAH 58 vba loops for-loop next

我有以下代码

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

所以我认为我可以简单地使用该语句Then Next x,但这会给出"no for statement声明"错误.

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

小智 82

你可以使用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
Run Code Online (Sandbox Code Playgroud)

  • +1关于古老的goto声明的逻辑和理性选择http://www.drdobbs.com/cpp/what-dijkstra-said-was-harmful-about-got/228700940 (9认同)

Jea*_*ett 45

您正在考虑continueJavaPython这样的语句,但VBA没有这样的本地语句,您不能Next像这样使用VBA .

您可以使用GoTo语句来实现类似于您尝试做的事情,但实际上,GoTo应该保留用于替代方案设计和不切实际的情况.

在你的情况下,只有一个"继续"条件,有一个非常简单,干净,可读的替代方案:

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

  • 当您在整个循环中有多个条件时,这样会更不干净和可读.随着代码越来越嵌套,它需要更多的顶空来让编码器尝试读取它.出于这个原因,GoTo在这里可能会更好,而Arlen Beiler的答案是另一个不错的解决方案. (8认同)

小智 18

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

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

  • 嗯,这基本上与[Arlen Beiler的较早答案](/sf/answers/1962317381/)相同,只是换行次数少了... (2认同)

Arl*_*ler 13

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


小智 8

几年后,但这是另一种选择.

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

  • 是的,但这是手头问题的标准选择,如果它不止一个`继续'条件,导致丑陋的嵌套 (2认同)