Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

End one Sub through another

Status
Not open for further replies.

kthureen

Programmer
May 28, 2003
6
US
Question: Is it possible to bring end one Sub by initiating another?

More specifically, I have a sub that is initiated by the user clicking a command button. I would like the user to be able to quit that sub by clicking a "Cancel" command button. Does anyone know how this can be done?
 
You could set a global varaible boolCancelClicked true when the cancel button is clicked then make sure you check it's value while executing the sub. Here's an example.

Option Explicit
Dim boolCancelClicked As Boolean
Private Sub cmdCancel_Click()
boolCancelClicked = True
End Sub
Private Sub cmdDoSomething_Click()
boolCancelClicked = False
Do Until 1 = 2
If boolCancelClicked = True Then
Exit Sub
End If
DoEvents
Loop
End Sub
 
You could have the click on the Cancel button set a global boolean variable to True, and have the other sub monitor the value of the boolean variable. When the boolean variable is True, execute an Exit Sub. You will probably need to throw in a DoEvents command in the sub to be exited to allow the update of the boolean variable.

I used to rock and roll every night and party every day. Then it was every other day. Now I'm lucky if I can find 30 minutes a week in which to get funky. - Homer Simpson
 
Just make sure to disable the first command button so the user can't click it again while the sub is running, because the DoEvents will cause the sub to run a second time, and that could cause all sorts of problems.

This also goes for any other controls, be they buttons or other types, that you may not want the user to click on while the sub is running.

Borrowing from the Java Doctors code:

Private Sub cmdDoSomething_Click()
cmdDoSomething.Enabled = False ' disable the button while sub is running
boolCancelClicked = False
Do Until 1 = 2
If boolCancelClicked = True Then
cmdDoSomething.Enabled = True ' reenable the button
Exit Sub
End If
DoEvents
Loop
cmdDoSomething.Enabled = True ' reenable the button
End Sub


Robert
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top