Trapping User Cancels

By default, the user can halt the execution of your VBA code by pressing either the ESC key or CTRL+BREAK. You can trap this action by using the EnableCancelKey property of the Application object. Using the statement

Application.EnableCancelKey = xlErrorHandler

causes the ESC or CTRL+BREAK keys to generate an error which will be trapped by the error handler set in your most recent On Error statement. The Err.Number generated by a user cancel is 18. Have your error handler check for this code and exit gracefully if it occurs.

You can also completely disable the user's ability to cancel program execution with

Application.EnableCancelKey = xlDisabled

You should be very careful when using this setting, however, because it prevents canceling program execution in the event of an endless loop. In practice, you'll want to explicitly set the EnableCancelKey depending on whether you're ready to ship production code or you're testing.

During testing it makes sense to be able to stop loops (endless or otherwise). But allowing the user to interrupt your code in the middle of a routine is not practical. Either you'll disable the cancel key or set it to your own handler, which will stop at the next appropriate point and/or clean up as needed. This cancel key setting is also an excellent candidate for using your bDEBUG flag.