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 Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Cancelling Routines

Status
Not open for further replies.

Denk

Programmer
Jan 4, 2000
22
0
0
GB
I have created a program which carries out quite lengthy calculations. I want to add an option to cancel the calculation at any point.<br><br>I added a Command Button to act as a Cancel button, but when this button is clicked the calculation routines continue.<br><br>How do I stop the calculation routines after the Cancel button has been pressed?
 
If you are using an iterative loop to perform the calculations you could perform a DoEvents inside the loop and immediately check the value of a variable set in the button's Click event.<br><br>If CancelThis = True then Exit Sub.<br><br>The DoEvents will slow down your calculations <i>considerably</i> but there aren't a lot of ways for a user to interrupt a loop. <p> <br><a href=mailto:InterruptX@excite.com>InterruptX@excite.com</a><br><a href= Contingency Implementation</a><br>Send me suggestions or comments on my current software project.
 
Depending on how many iterations are in the loop, you could increment a counter variable and only call DoEvents every 10 or 20 (or whatever) iterations.&nbsp;&nbsp;
 
Here is a trick for DoEvents.<br>Notice the &quot;stop&quot; button does not even have<br>to be in your loop.<br>1-Put a Boolean in your Declarations.<br>2-Dim a &quot;throw-away&quot; variable before<br>&nbsp;&nbsp;entering your calculations.<br>3-Increment the variable in the loop<br>&nbsp;&nbsp;and use MOD to check it. This will<br>&nbsp;&nbsp;increase the speed of your loop, because<br>&nbsp;&nbsp;DoEvents will be triggered less often.<br><br>'Declarations Section<br>Dim Quit As Boolean<br><br>'Stop Button Code<br>Private Sub cmdStop_Click()<br>&nbsp;Quit=True<br>End Sub<br><br>'Code for Calculations<br>Private Sub Calculate()<br>Quit=False&nbsp;&nbsp;'Set Quit=False each time<br>Dim t As long<br>Start loop&nbsp;&nbsp;'Calculations Start<br>'code<br>t=t+1&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'Increment t<br>If t MOD 100 Then DoEvents&nbsp;&nbsp;'Let VB do other things.<br>If Quit Then Exit Sub&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'Exit if Stop Button Clicked<br>if t&gt;20000 then t=0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'reset t now and then<br>'code<br>'code<br>Finish loop<br>End Sub<br>
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top