In VBA on Excel, I have a loop over several thousands of cells, which takes some minutes.
Is it possible to abort a long term loop (if so, how) / can I build a button or something like that to interrupt this loop manually?
Building a button and overlaying it with a macro is not a problem, only the code itself.
#2 – Break Do Until Loop For example, if we wish to exit the loop when the variable “k” value becomes 6, we need to enter the criteria as IF k = 6 and then exit the loop. It will run the loop until the variable value becomes 6. After that, it will exit the loop.
Step 1: Open a new module go to the VBA window and in that select Module from the Insert menu option. Step 2: This will take us to a new module in VBA. Now in that module write Subcategory in the name of VBA Break For Loop or in any other name which defines its meaning. Step 3: Now define a DIM as any alphabet or word.
If the Macro is simply in a continuous loop or is running for too long you can use one of these keyboard shortcuts to kill it: Esc hit the Escape key. Ctrl + Break hit Ctrl key and then the break key, which is also the pause key.
When Excel is busy executing your macro, it won't respond to a button.
You have three options here:
Ctrl+Break
keys (as apposed to a button)Application.ScreenUpdating
to
False
will help)DoEvents
in the inner loop. This
way, Excel will resond to buttons in
the meantime. The macro this button would trigger would just set a global variable to True
(obviously, your inner loop should check this variable on each iteration, and exit if it's True
).Application.EnableCancelKey
could be the thing, you are looking for.
See the example code on the linked url, on passing the control to error handler when user presses escapes.
In addition to other answers,
Lets say you want to break the code and still perform certain actions in your code, You can do so by capturing the interrupt and handling it
You can use Err.Number to capture the error number
Specifically, Err.Number = 18 refers to user breaks
Sub handleError()
On Error GoTo MyErrorHandler
Application.EnableCancelKey = xlErrorHandler
'Just an example to show something is running
For i = 0 To 900000
Range("A1") = i
Next i
MyErrorHandler:
If Err.Number = 18 Then '18 =User interrupt
MsgBox " You clicked Ctrl + Break "
Exit Sub
End If
End Sub
Add a call to DoEvents inside the loop.
Add a public boolean module level flag variable
Add a button to the UI
In the event handler for the button set the flag true
in the loop check the variable, if it is true abort the loop.
I've used this in an Excel userform but not with buttons on a worksheet.
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