Playing Sound From Excel

Category: General VBA | [Item URL]

Excel developers can sometimes benefit by including sound in their application. For example, you can use a sound to provide audible feedback when a specific cell exceeds a particular value. Or, you just might like to add some simple sound effects to spice things up a bit.

You can play sounds by using a simple Windows API call and some VBA code.

Are Sounds Supported?

Not all systems support sound. If you need to determine if sounds are supported, use the CanPlaySounds method. Here's an example:

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 dogbark.wav, which is assumed to be in the same directory as the workbook.

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 playing. If you would like code execution to stop while the sound is playing, use this statement:

    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 file. Executing the StopMIDI subroutine will stop playing the MIDI file.

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


Search for Tips


All Tips

Browse Tips by Category

Tip Books

Needs tips? Here are two books, with nothing but tips:

Contains more than 200 useful tips and tricks for Excel 2007 | Other Excel 2007 books | Amazon link: John Walkenbach's Favorite Excel 2007 Tips & Tricks

Contains more than 100 useful tips and tricks for Excel 2013 | Other Excel 2013 books | Amazon link: 101 Excel 2013 Tips, Tricks & Timesavers

© Copyright 2016, J-Walk & Associates, Inc.
Privacy Policy