View Single Post
  #2   Report Post  
Posted to microsoft.public.excel.programming
joeu2004 joeu2004 is offline
external usenet poster
 
Posts: 2,059
Default How to stop a macro

On Apr 3, 3:48*pm, DA wrote:
I'd like a macro to stop after 20 seconds, if it has
not finished. What is the easiest way to do this?


Press ctrl+Break. (On my laptop, it is ctrl+alt+Pause.) That usually
interrupts the procedure and allows you debug or end.

Oh, did you mean programmatically? ;-)

See the following example. Essentially, OnTime is used to call a
procedure after a prescribed amount of time (5 sec, in the example).
When the timeOut function is called, it sets a global variable stopIt
to True. When the main procedure (doit) sees that stopIt is True, the
main procedure exits the loop.

However, this works on if the main procedure yields the CPU
periodically. See the use of DoEvents() in the main procedure. I
imagine that can be costly in execution time.

Also, there are many other conditions that will prevent the timeOut
procedure from running when the timer pops.

See http://www.cpearson.com/excel/OnTime.aspx for another method. I
don't know if avoids any or all of the above pitfalls.

Example....

Private stopIt As Boolean
Private st As Double

Sub doit()
'* see also http://www.cpearson.com/excel/OnTime.aspx
stopIt = False
st = Now
Application.OnTime st + TimeSerial(0, 0, 5), "timeOut"
myst = Timer
Do
'* abort if no timeout after 10 sec
If Timer - myst 10 Then MsgBox "no timeout": Exit Sub

'* must use DoEvents to allow timeOut to run.
'* comment out following line to see what happens
x = DoEvents()
Loop Until stopIt
MsgBox "stopit"
End Sub

Private Sub timeOut()
stopIt = True
et = Now
MsgBox "timeOut" & Format(st, " hh:mm:ss") & _
Format(et, " hh:mm:ss")
End Sub