Playing Sound From Excel
Excel developers can sometimes benfit 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.
In Excel 5 and Excel 95, an easy way to add sound to your workbook is to use a sound note -- a cell note that contains a WAV file. Select Insert Note to display the Cell Note dialog box. Then click Import to import a WAV file. Then you can play the sound with a VBA statement such as:
The sound note feature is no longer available in Excel 97. However, you can still play sounds by using a simple Windows API call.
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
Download an Example
You can download a copy of Sound-Proof -- an application that uses WAV files to
"read back" a range of values. Click here for