跳出While...Wend循环

126

我正在使用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<=10...Wend`这样的条件语句。

4个回答

227

只有通过GOTO或退出外部块(Exit sub/function或另一个可退出循环)才能提前退出While/Wend循环。

改用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 有什么区别? - GMSL
@GMSL while基本上是Do While的一个更糟糕的版本。循环行为是相同的。https://excelmacromastery.com/vba-while-loop/ - Dan

0

那么在循环中设置“While”测试参数,使得循环在下一次迭代时结束怎么样?例如...

OS = 0
While OS <> 1000 
OS = OS + 1 
If OS = 500 Then OS = 1000 
Wend

好的,这是一个完全没有意义的例子,但它展示了原则...


0

另一个选择是将一个标志变量设置为 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

0

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接