Stop a loop

T

tiredoftrying

I have a command button that starts a loop/counter (using the access example
in help), how can stop the loop Prematurely with another command button -
before it reaches its count
 
J

Jesper F

I have a command button that starts a loop/counter (using the access
example
in help), how can stop the loop Prematurely with another command button -
before it reaches its count

I've been bugged by the same for a while.
I think the solution is to have a global variable. You can set the global
variable to false when you hit your cancel-button.
Your loop should check whether the global variable is false everytime it
runs and break if it is.
Something like:

Public stoploop as boolean
-----------
Private Sub MyLoop()
For i=0 to 100000
If stoploop=true then
exit sub
End if
Next
End sub

Private Sub cmdCancel_Click()
stoploop=true
End sub



Jesper Fjølner
 
S

Stefan Hoffmann

hi,

take a nap :)
I have a command button that starts a loop/counter (using the access example
in help), how can stop the loop Prematurely with another command button -
before it reaches its count
Declare a stop variable in your form and use DoEvents:

Private m_StopLoop As Boolean

Private Sub cmdStopLoop_Click()

bStopLoop = True

End Sub

Private Sub cmdDoLoop_Click()

Dim l As Long

m_StopLoop = False
For l = 0 To 123456789
'payload
If m_StopLoop Then Exit For
Interaction.DoEvents
Next l

End Sub


mfG
--> stefan <--
 
K

Klatuu

It will not work as written. I just did a little test on it. The problem
is, th code is busy executing, and will not respond to Cancel Click event.
To make it work, you will need to put a DoEvents inside the For Next loop,
but outside the If End If.
 
J

Jesper F

It will not work as written. I just did a little test on it. The problem
is, th code is busy executing, and will not respond to Cancel Click event.
To make it work, you will need to put a DoEvents inside the For Next loop,
but outside the If End If.

Yeah, I forgot that.


Jesper
 
Top