I tried to use EnableCancelKey to allow myself to stop the music and still make the appropriate API calls to reset the midi out. It didn’t work so well for me. Here’s another way.
I created two global variables. One to determine whether the procedure was already running and one to determine if the user wants to stop the procedure.
Public gbAppStarted As Boolean
These are declared in a standard module outside of any procedures so that they’re accessible from anywhere in the project.
Next, I modified the click event of the button that’s used to start the procedure.
If gbAppStarted Then
gbUserCancel = True
gbAppStarted = False
gbAppStarted = True
If the procedure is running (gbApppStarted is True), then it assumed the user wants to stop the procedure and gbUserCancel is set to True. If the procedure is not running, it’s called so that it starts running. Finally, I modified the PlayWorksheetNotes procedure to check the gbUserCancel variable.
Dim r As Long
On Error GoTo ErrHandler
gbUserCancel = False
For r = 2 To Application.CountA(Range(“A:A”))
If gbUserCancel Then Err.Raise 9999
Call PlayMIDI(Cells(r, 1), Cells(r, 2), Cells(r, 3))
On Error Resume Next
If Err.Number <> 9999 Then
If the button is clicked while the notes are playing, gbUserCancel is set to True. Inside the loop, that variable is check. Once True, an error is raised and the error handler is called. Any error that’s not the one I made up (9999) is shown in a message box. Then the procedure resumes at ProcExit which resets the midi out for the future.