Break out of a While...Wend loop

Priyank Thakkar picture Priyank Thakkar · Aug 30, 2012 · Viewed 379.4k times · Source

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

Answer

Alex K. picture Alex K. · Aug 30, 2012

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)