Exit a while loop in VBS/VBA

前端 未结 6 1790
天涯浪人
天涯浪人 2020-12-11 14:25

Is there a method of exiting/breaking a while in VBS/VBA?

Following code won\'t work as intended:

num = 0
while (num < 10)

    if (s         


        
6条回答
  •  心在旅途
    2020-12-11 14:58

    I know this is old as dirt but it ranked pretty high in google.

    The problem with the solution maddy implemented (in response to rahul) to maintain the use of a While...Wend loop has some drawbacks

    In the example given

    num = 0
    While num < 10
      If status = "Fail" Then
        num = 10
      End If
      num = num + 1
    Wend
    

    After status = "Fail" num will actually equal 11. The loop didn't end on the fail condition, it ends on the next test. All of the code after the check still processed and your counter is not what you might have expected it to be.

    Now depending on what you are all doing in your loop it may not matter, but then again if your code looked something more like:

    num = 0
    While num < 10
      If folder = "System32" Then
        num = 10
      End If
      RecursiveDeleteFunction folder
      num = num + 1
    Wend
    

    Using Do While or Do Until allows you to stop execution of the loop using Exit Do instead of using trickery with your loop condition to maintain the While ... Wend syntax. I would recommend using that instead.

提交回复
热议问题