Exit a while loop in VBS/VBA

maddy picture maddy · Aug 13, 2009 · Viewed 135.9k times · Source

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 (status = "Fail") then
        exit while
    end if

    num = num+1
wend

Answer

Helen picture Helen · Aug 13, 2009

VBScript's While loops don't support early exit. Use the Do loop for that:

num = 0
do while (num < 10)
  if (status = "Fail") then exit do
  num = num + 1
loop