Aborting a loop

  • Thread starter Thread starter Dave
  • Start date Start date
D

Dave

I have code behind a form that performs a loop through a large recordset.

How can I allow the user to abort the loop on demand (i.e., click on a
button to stop the looping and exit the sub)?

Once the loop is running, the form is not enabled. In other words, I cannot
click on a form control until the loop completes. Put another way, no form
events are registered until the loop completes execution.

What can I do to allow the user to abort the loop?
 
Dave said:
I have code behind a form that performs a loop through a large
recordset.

How can I allow the user to abort the loop on demand (i.e., click on a
button to stop the looping and exit the sub)?

Once the loop is running, the form is not enabled. In other words, I
cannot click on a form control until the loop completes. Put another
way, no form events are registered until the loop completes execution.

What can I do to allow the user to abort the loop?

Inside the loop, execute the DoEvents statement to allow form events to
fire. Let the command button's Click event code set a global boolean
variable to True (having initialized it to False before entering the
loop. On each iteration of the loop, check the value of that variable
to see if you should bail out. Here's an example:

'----- start of example code for form's module -----
Dim mfBailOut As Boolean

Private Sub cmdCancel_Click()

mfBailOut = True

End Sub

Private Sub cmdRunLongProcess_Click()

' ...

Do Until rs.EOF

DoEvents

If mfBailOut Then
MsgBox "Process cancelled."
Exit Do
End If

' ... code to process current record ...

.MoveNext
Loop


End Sub
'----- end of example code -----

You can speed things up by only running the DoEvents every n iterations
through the loop, where n is some number determined by experimentation.
 
Back
Top