129

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

4 Answers 4

234

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)

Sign up to request clarification or add additional context in comments.

2 Comments

What's the difference between a While and a Do While please?
@GMSL while is basically a worse version of Do While. The looping behavior is identical. excelmacromastery.com/vba-while-loop
1

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 

Comments

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 

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.