Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop VBA code running?

Tags:

excel

vba

Say I have a button embedded into my spreadsheet that launches some VBA function.

Private Sub CommandButton1_Click()
    SomeVBASub
End Sub

Private Sub SomeVBASub
    DoStuff
    DoAnotherStuff
    AndFinallyDothis
End Sub

I'd like to have an opportunity to have some sort of a "cancel" button that would stop SomeVBASub execution at an arbitrary moment, and I'm not into involving Ctrl+Break here, 'cause I'd like to do it silently.

I guess this should be quite common issue, any ideas?

Thanks.

like image 287
Kirill Leontev Avatar asked Oct 20 '10 16:10

Kirill Leontev


1 Answers

Add another button called "CancelButton" that sets a flag, and then check for that flag.

If you have long loops in the "stuff" then check for it there too and exit if it's set. Use DoEvents inside long loops to ensure that the UI works.

Bool Cancel
Private Sub CancelButton_OnClick()
    Cancel=True
End Sub
...
Private Sub SomeVBASub
    Cancel=False
    DoStuff
    If Cancel Then Exit Sub
    DoAnotherStuff
    If Cancel Then Exit Sub
    AndFinallyDothis
End Sub
like image 73
Jamie Treworgy Avatar answered Oct 22 '22 16:10

Jamie Treworgy