【发布时间】:2015-03-17 22:33:57
【问题描述】:
由于 VBA 没有 Continue 语句(或任何类似性质的语句),那么完成相同事情的另一种方法是什么。
【问题讨论】:
-
那个旧的备用 goto 语句怎么样?
标签: vba
由于 VBA 没有 Continue 语句(或任何类似性质的语句),那么完成相同事情的另一种方法是什么。
【问题讨论】:
标签: vba
一种方法是使用封闭的 Do...Loop。当然,这在另一个 Do...Loop 中是行不通的,但我们在大多数编程语言中都会遇到这种情况。
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
【讨论】:
exit do 应该被删除,而应该使用loop until true 或loop while false。
在不提供 Continue 语句的语言中,最好的方法是将剩余的代码块简单地包装在 if 条件中。
For i=1 to 10
'some code here
If I_want_to_finish_this_loop
'do your thing
End If
Next i
这避免了使用 Goto,您唯一的成本就是反转条件。
如果您有多个地方需要继续,最好的办法是在代码中放置一个继续标签,然后转到它。
For i=1 to 10
'some code here
If I_dont_want_to_finish_this_loop
Goto Continue
End If
'finish the loop
:Continue
Next i
【讨论】:
if 语句。