【问题标题】:What are some ways to simulate a Continue statement in VBA? [duplicate]有哪些方法可以在 VBA 中模拟 Continue 语句? [复制]
【发布时间】:2015-03-17 22:33:57
【问题描述】:

由于 VBA 没有 Continue 语句(或任何类似性质的语句),那么完成相同事情的另一种方法是什么。

【问题讨论】:

  • 那个旧的备用 goto 语句怎么样?

标签: vba


【解决方案1】:

一种方法是使用封闭的 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 trueloop while false
【解决方案2】:

在不提供 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 语句。
  • 哈维先生,你真是在开玩笑!
  • 所有其他选项都比较复杂。
  • goto 语句并不复杂。
猜你喜欢
  • 1970-01-01
  • 2013-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-10
  • 2013-07-17
  • 1970-01-01
  • 2012-01-10
相关资源
最近更新 更多