2011-05-05 104 views
37

我有以下代码持续循环

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,但是这给了“不为语句声明”的错误。

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

+0

谢谢你们纠正我拼写错误,我知道我吮吸它,并且很感激人们会花时间帮助我。欢呼声 – DevilWAH 2013-11-20 13:59:00

回答

29

您不能使用Next那样的。您可以使用GoTo声明来实现类似于您试图执行的操作,但实际上,GoTo应该保留用于替代方法设计且不切实际的情况。

在你的情况,有一个非常简单的,干净的,可读的选择:

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

当你在整个循环中有几个条件时,这不太干净和可读。随着代码更深入的嵌套,编码器试图读取它需要更多的空间。出于这个原因,GoTo在这里可能会更好,而Arlen Beiler的回答是另一个体面的解决方案。 – pettys 2016-05-27 15:32:57

+0

我同意,这将是更好的答案 - 一个不同的问题。不是这个。 – 2016-05-28 10:18:11

+0

听起来好像我们同意,对于那些寻找VBA缺乏“继续”声明的更一般方法的人来说,下面的替代答案具有优势。我的意图仅仅是通过权衡一般情况下的权衡来加深讨论。 – pettys 2016-05-31 17:26:28

65

您可以使用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

+1对古老goto声明的逻辑和理性选择+1 http://www.drdobbs.com/cpp/what-dijkstra-said-was-harmful-about-got/228700940 – 2015-01-19 20:24:53

5

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

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 
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 
+0

这看起来是最好的方式退出使用Goto继续我见过的For循环。我想象一下,在其他情况下,您也可以采用相同的方法来避免Goto ... – tobriand 2015-05-29 16:24:25

+0

好的答案。 Alfredo Yong的回答是一样的想法,但阿尔弗雷多的答案的紧凑性使其对我更具可读性。 – pettys 2016-05-27 15:33:50

0

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

Do 

    Do 

     If I_Don't_Want_to_Finish_This_Loop Then Exit Do 

     Exit Do 

    Loop 

Loop Until Done 

这避免了 “转到意大利面条”

12

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

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 
+0

!!!天才 !!!!! – pashute 2016-11-09 15:06:42