More Dueling Banjos

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 gbUserCancel As Boolean
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.

Private Sub CommandButton1_Click()
    If gbAppStarted Then
        gbUserCancel = True
        gbAppStarted = False
        gbAppStarted = True
    End If
End Sub

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.

Sub PlayWorksheetNotes()
    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
        Cells(r, 2).Select
        Call PlayMIDI(Cells(r, 1), Cells(r, 2), Cells(r, 3))
    Next r
    On Error Resume Next
    midiOutReset hMidiOut
   Exit Sub
    If Err.Number <> 9999 Then
        MsgBox Err.Description
    End If
   Resume ProcExit
End Sub

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.

Posted in Uncategorized

One thought on “More Dueling Banjos

  1. yes, Dick, i did something similar:

    Private Sub CommandButton1_Click()
    If [a1] = 2 Then
    [a1] = 1
    Else: [a1] = 2
    End If
    End Sub


    sub pasasd
    ‘before each note
    If [a1].Value = 2 Then GoTo dug
    ”continue procedure

    midiOutClose hMidiOut
    End Sub

    And I start and stop the playing with the button.
    Im just curious as to how to hold onto the variables that seem to be destroyed when there’s a runtime error or i hit stop

Posting code? Use <pre> tags for VBA and <code> tags for inline.

Leave a Reply

Your email address will not be published.