How to allow users to quit out of long-running VBA tasks?

user-controls, user-interface, vba

Solution

You need DoEvents and a variable whose scope is greater than the scope of what you're running. That is, if it's just a procedure, you need a module level variable. If it's more than one module, you need a global variable. See here

Stopwatch at DDoE

Normally, the VB engine will tie up the processor until it's done. With DoEvents, however, VB allows the processor to work on whatever is next in the queue, then return to VB.

Problem

I have a routine that examines thousands of records looking for discrepancies. This can take upwards of 5 minutes to complete and although I provide a progress bar and elapsed time count, I'm not sure I want to encourage folk pressing ctrl-break to quit the report should it be taking longer than expected. A button in the progress bar won't work as the form is non-modal, so is there any neat way of allowing users to quit in this situation?

Original source