Question : How do I pause a running program in VBA

In an Excel worksheet, say I have a column called program counter and another column has the function that it should call. I have created a userform as illustrated in the image. Enter the program counter which you want your program to run up to. For example, if you enter program counter as 20 and click Run, the program runs from 1 till 20. However, if it was in the middle of running and you click on 'Pause', the program should stop running. How can I do this? How do I resume upon pressing t he resume button? Any help would be  much appreciated. Thanks.
Attachments:
 
Userform
Userform
 

Answer : How do I pause a running program in VBA

Here's a very basic version of what you need. Have a form with three command buttons cmdStart, cmdPause and cmdResume, a textbox textbox1 and a label label1.

I have commented all the lines of the code so hopefully you can see what is going on:

The label is there so you can see your counter (and I'm using it to preserve the ctr value when paused).

It needs a check that the textbox actually holds a legal value before you start, I'd put this under the start button and only call the increment routine if the value is a good one.

On testing it, if you are just going to let it run you will need to use a value something like 20000 or you won't be able to pause fast enough.


Option Explicit
Dim runstatus As Boolean 'whether the loop can run or not. form level so all the procedures can see it
Private Sub cmdPause_Click()
   runstatus = False 'set the status so the loop will stop
End Sub
Private Sub cmdResume_Click()
   increment CLng(Label1.Caption) 'restart the counting using the preserved value of the counter
End Sub
Private Sub cmdStart_Click()
   increment 1 'start the counting from 1
End Sub
Private Sub increment(ctr As Long)
runstatus = True 'make sure the loop can run
Do While runstatus = True And ctr < Val(TextBox1.Value) 'only enter this loop if runstatus is true and the ctr hasn't finished
   ctr = ctr + 1 'increment the counter
   Label1.Caption = ctr 'output the counter value, using the label caption as a store of the current value
   DoEvents 'so the label can update its caption, and to allow the pause button to be pressed
Loop 're-enter the loop if the loop conditions are still true
End Sub

I'm sorry I took so long to get back to you, but if you need any more explanation please ask.

Random Solutions  
 
programming4us programming4us