126

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

pgSystemTester
  • 8,979
  • 2
  • 23
  • 49
Priyank Thakkar
  • 4,752
  • 19
  • 57
  • 93

4 Answers4

223

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)

Alex K.
  • 171,639
  • 30
  • 264
  • 288
  • What's the difference between a `While` and a `Do While` please? – GMSL Apr 12 '21 at 14:11
  • @GMSL while is basically a worse version of Do While. The looping behavior is identical. https://excelmacromastery.com/vba-while-loop/ – Dan Mar 14 '23 at 20:44
0

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
Sam Martin
  • 21
  • 4
0

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
deseosuho
  • 958
  • 3
  • 10
  • 28
0

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...

RannochRob
  • 51
  • 5