I have a Do .. While loop in which two For.. loops are nested; the first For.. loop counts up from 1 to X, the second loop counts down from X to 1. This is currently repeated ad infinitum.
Now, I want the user to be able to 'interrupt' this infinite loop, and that the program, upon interruption of the loop, executes XYZ.
I've tried using a toggle button in combination with the Do.. While loop, but while the aforementioned loop is running, no input is accepted. The state of the button does not change when clicked if the code is running the loop.
Any suggestions are highly appreciated.
In VBA, you can stop your macro execution manually with the Esc key or by pressing Ctrl+Break.
AutoCAD to Excel - VBA Programming Hands-On!A Exit For statement is used when we want to exit the For Loop based on certain criteria. When Exit For is executed, the control jumps to the next statement immediately after the For Loop.
Option 1: Hold the Esc key down for more than a few seconds. Option 2: Press CTRL+BREAK. Option 3: CTRL + ALT + DEL to end process & have Auto recover when you re-open.
The key is to include a DoEvents
in the loops. This allows Excel to process things like a button click while running the code
Here's an outline. Assign macro ButtonClick
to the button. Main
will run indefinately until the button is clicked.
Option Explicit
Dim bBreak As Boolean
Sub ButtonClick()
bBreak = True
End Sub
Sub Main()
Dim X As Long
Dim i As Long
bBreak = False
Do While True
X = 1000
For i = 1 To X
If bBreak Then
Exit Do
End If
DoEvents
Next
For i = X To 1 Step -1
If bBreak Then
Exit Do
End If
DoEvents
Next
Loop
If bBreak Then XYZ
End Sub
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With