If I'm running a Do... Until or a For... Next loop in a button click event, is there a way I can allow the user to click the same button while the loop is running and escape the loop?

You can use Exit While , Exit For , Exit Sub , etc.

Use a Variable like bLoopCancel to control your loop.

Initially set it false.

Code your loop so that if bLoopCancel is true, your loop terminates

When a loop is executing (Do, for ..) it may not respond to the user.

Use Application.DoEvents() inside the loop now the loop will respond the user.

Change the bLoopCancel in any user interface that user want to stop the loop (in ur case it is button click)

Try this in code

Never use Application.DoEvents() -- it has way too many unintended effects. If your application is in the middle of a long-running loop and you use .DoEvents() to force the form to update it will also allow them to click on the "X" in the top-right and close the form/application, for example. Handle these operations in another thread and report progress back to the GUI.

You can use Exit While , Exit For , Exit Sub , etc.

Thanks for that. As you can see, I'm not a pro at this.

Okay, but I only want to exit the loop when the user clicks the button again in whose click event the loop is running. (Sorry, hard for me to explain)

I'll try another way: The user clicks the button and that starts the loop. I want the loop to run until the user clicks the same button again. Then I want to exit the loop.

Well what is this loop going to be doing exactly? You could use a background worker, a thread, the thread pool, etc for doing this loop.

Thanks for that. As you can see, I'm not a pro at this.

Okay, but I only want to exit the loop when the user clicks the button again in whose click event the loop is running. (Sorry, hard for me to explain)

I'll try another way: The user clicks the button and that starts the loop. I want the loop to run until the user clicks the same button again. Then I want to exit the loop.

Then you would half to use if statements (If, Then, Else, Elseif) so it would be like
If Textbox1.text = o then
loop start
else
loop end
end if


something like that and make your loop increase the value or edit whats in textbox1.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.