Excel Macro Play Sound

You might also like

Download as xlsx, pdf, or txt
Download as xlsx, pdf, or txt
You are on page 1of 4

If Not Application.

CanPlaySounds Then
MsgBox "Sorry, sound is not supported on your system."
Exit Sub
End If

Example: Playing a WAV File


The example below contains the API function declaration, plus a simple subroutine to play a sound file called dogbar

Private Declare Function PlaySound Lib "winmm.dll" _


Alias "PlaySoundA" (ByVal lpszName As String, _
ByVal hModule As Long, ByVal dwFlags As Long) As Long

Const SND_SYNC = &H0


Const SND_ASYNC = &H1
Const SND_FILENAME = &H20000

Sub PlayWAV()
WAVFile = "dogbark.wav"
WAVFile = ThisWorkbook.Path & "\" & WAVFile
Call PlaySound(WAVFile, 0&, SND_ASYNC Or SND_FILENAME)
End Sub

In the example above, the WAV file is played asynchronously. This means execution continues while the sound is pla

Call PlaySound(WAVFile, 0&, SND_SYNC Or SND_FILENAME)

Example: Playing a MIDI File


If the sound file is a MIDI file, you'll need to use a different API call. The PlayMIDI subroutine starts playing a MIDI fil

Private Declare Function mciExecute Lib "winmm.dll" _


(ByVal lpstrCommand As String) As Long

Sub PlayMIDI()
MIDIFile = "xfiles.mid"
MIDIFile = ThisWorkbook.Path & "\" & MIDIFile
mciExecute ("play " & MIDIFile)
End Sub

Sub StopMIDI()
MIDIFile = "xfiles.mid"

MIDIFile = ThisWorkbook.Path & "\" & MIDIFile


mciExecute ("stop " & MIDIFile)
End Sub
to play a sound file called dogbark.wav, which is assumed to be in the same directory as the workbook.

continues while the sound is playing. If you would like code execution to stop while the sound is playing, use this statement:

broutine starts playing a MIDI file. Executing the StopMIDI subroutine will stop playing the MIDI file.
se this statement:

You might also like