tracktraining said:
Hi All,
I would like to create a cancel message that appears while a sub is running.
So, when the user hit the cancel button on the message box (or userform),
then the sub will exit and start the program from the beginning. And if the
user doens't hit the cancel button, then the sub will continue to work as is.
Any help is much appreciated.
thanks,
tracktraining
Consider this approach.
Here is code for a form that contains a command button and a text box:
Option Explicit
Private Sub CommandButton1_Click()
IsCancel = True
End Sub
And here is module code that would contain your sub:
Option Explicit
Public IsCancel As Boolean
Sub endlessloop()
Dim i As Long
IsCancel = False
UserForm1.Show vbModeless
Do Until IsCancel
UserForm1.TextBox1.Value = i
i = i + 1
DoEvents
Loop
MsgBox "you canceled"
UserForm1.Hide
End Sub
The keys to make this work are
- the global variable in the module, which the form can set
- the use of vbModeless when showing the form
- checking the state of the global flag "IsCancel" that signals when to
stop the loop
You need to be careful with this though. In real life it is typically
more difficult to know when to check the flag. By the same token it is
more difficult to know what to do when the flag is tripped. Variables
usually need to be reset, etc.
Also, unless you are very careful, you /do not/ want to call the sub
again from within itself, especially if there is more code after the
call. Why? Because the self-referential call will push the old instance
on the stack, and that will be waiting to resume execution later when
the new instance completes its uninterrupted mission. (Just imagine if
the user click cancel a dozen times... a dozen incomplete versions of
the sub will be stacked up, waiting to finish).