vba 跳出 While...Wend 循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12200834/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 13:55:14  来源:igfitidea点击:

Break out of a While...Wend loop

excelvbawhile-loop

提问by Priyank Thakkar

I am using a While...Wend loop of VBA.

我正在使用 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

I don't want to use condition like `While count<=10...Wend

我不想使用像`While count<=10...Wend 这样的条件

回答by Alex K.

A While/Wendloop can only be exited prematurely with a GOTOor by exiting from an outer block (Exit sub/functionor another exitable loop)

While/Wend循环只能与一个过早地退出GOTO或通过从外块(退出Exit sub/function或另一exitable环)

Change to a Doloop instead:

改为Do循环:

Do While True
    count = count + 1

    If count = 10 Then
        Exit Do
    End If
Loop

Or for looping a set number of times:

或者循环一定次数:

for count = 1 to 10
   msgbox count
next

(Exit Forcan be used above to exit prematurely)

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

回答by Sam Martin

Another option would be to set a flag variable as a Booleanand then change that value based on your criteria.

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