Break out of a While...Wend loop
ExcelVbaWhile LoopExcel Problem Overview
I am using a While...Wend loop of VBA.
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
Excel Solutions
Solution 1 - Excel
A While
/Wend
loop can only be exited prematurely with a GOTO
or by exiting from an outer block (Exit sub
/function
or another exitable loop)
Change to a Do
loop instead:
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 For
can be used above to exit prematurely)
Solution 2 - Excel
Another option would be to set a flag variable as a Boolean
and then change that value based on your criteria.
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
Solution 3 - Excel
The best way is to use an And
clause in your While
statement
Dim count as Integer
count =0
While True And count <= 10
count=count+1
Debug.Print(count)
Wend
Solution 4 - Excel
What about setting the 'While' test perameters in the loop so that the loop ends on the next iteration. For example...
OS = 0
While OS <> 1000
OS = OS + 1
If OS = 500 Then OS = 1000
Wend
Ok, that's a totally pointless example but it shows the principle...