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)
Jea*_*ett 45
您正在考虑continue像Java或Python这样的语句,但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)
小智 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)
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)