【问题标题】:Break out of a While...Wend loop跳出一个 While...Wend 循环
【发布时间】:2012-08-25 09:57:41
【问题描述】:

我正在使用 VBA 的 While...Wend 循环。

Dim count as Integer

While True
    count=count+1

    If count = 10 Then
        ''What should be the statement to break the While...Wend loop? 
        ''Break or Exit While not working
    EndIf
Wend

我不想使用像`While count

【问题讨论】:

    标签: excel vba while-loop


    【解决方案1】:

    While/Wend 循环只能通过GOTO 或从外部块退出(Exit sub/function 或其他可退出循环)提前退出

    改为 Do 循环:

    Do While True
        count = count + 1
    
        If count = 10 Then
            Exit Do
        End If
    Loop
    

    或者循环一定次数:

    for count = 1 to 10
       msgbox count
    next
    

    (上面可以使用Exit For提前退出)

    【讨论】:

    • 请问WhileDo While 有什么区别?
    【解决方案2】:

    另一种选择是将标志变量设置为Boolean,然后根据您的条件更改该值。

    Dim count as Integer 
    Dim flag as Boolean
    
    flag = True
    
    While flag
        count = count + 1 
    
        If count = 10 Then
            'Set the flag to false         '
            flag = false
        End If 
    Wend
    

    【讨论】:

      【解决方案3】:

      最好的方法是在While 语句中使用And 子句

      Dim count as Integer
      count =0
      While True And count <= 10
          count=count+1
          Debug.Print(count)
      Wend
      

      【讨论】:

        猜你喜欢
        • 2015-04-08
        • 1970-01-01
        • 2015-12-20
        • 2016-04-08
        • 2021-08-31
        • 2016-01-18
        • 1970-01-01
        • 2020-01-03
        • 2013-05-06
        相关资源
        最近更新 更多