I have a solution to play MIDI files from Excel that does not produce an error, previously caused by clicking "Stop MIDI" when no file has been played yet, or by attempting to play another file while one is running.
The Stop MIDI command button is only enabled after a MIDI file has starting playing. At the same time, the cell clicked to begin the playing (the cell contains a "P" indicating a MIDI file is available) causes the font color in that column to be changed to a light gray. As long as the font color is light gray, no further files can be played. When Stop MIDI button is clicked, the button is immediately disabled and the light gray is changed to black.
The result is that the Stop button cannot be pressed at the wrong time, and a subsequent MIDI file can only be played after the Stop button is pressed.
MIDI Playing and Stopping code is shown below. Tests for whether or not a file can be played are done in the worksheet SelectionChange event, and the Play_MIDI code will not be called if the font color in the column with "P" is light gray.
Code:
Private Declare Function mciExecute Lib "winmm.dll" (ByVal lpstrCommand As String) As Long
Public isMIDIPlaying As Boolean
Sub Play_MIDI(strMIDIFile As String)
If isMIDIPlaying Then Exit Sub
If Application.CanPlaySounds Then
strMIDIFile = ThisWorkbook.Path & Application.PathSeparator & strMIDIFile
If (VBA.Dir(strMIDIFile) <> "") Then
'The double quotes Chr$(34) are needed when the file path contains spaces.
'First OPEN and then PLAY.
mciExecute ("OPEN " & VBA.Chr$(34) & strMIDIFile & VBA.Chr$(34) & " ALIAS jingle")
mciExecute ("PLAY jingle")
isMIDIPlaying = True
End If
End If
End Sub
Sub Stop_MIDI(strMIDIFile As String)
If Application.CanPlaySounds Then
strMIDIFile = ThisWorkbook.Path & Application.PathSeparator & strMIDIFile
If (VBA.Dir(strMIDIFile) <> "") And isMIDIPlaying Then
mciExecute ("CLOSE jingle")
End If
End If
isMIDIPlaying = False
Exit Sub
End Sub
RESOLVED