Playing WAV-files using VBA in Microsoft Excel

It's easy to play soundfiles in WAV-format. You only need to know the filename of the sound you want to play,
and decide if you want the macro to wait while the sound plays or not. Here is an example:

Public Declare Function sndPlaySound Lib "winmm.dll" _
Alias "sndPlaySoundA" (ByVal lpszSoundName As String, _
ByVal uFlags As Long) As Long

Sub PlayWavFile(WavFileName As String, Wait As Boolean)
    If Dir(WavFileName) = "" Then Exit Sub ' no file to play
    If Wait Then ' play sound before running any more code
        sndPlaySound WavFileName, 0
    Else ' play sound while code is running
        sndPlaySound WavFileName, 1
    End If
End Sub

Sub TestPlayWavFile()
    PlayWavFile "c:\foldername\soundfilename.wav", False
    MsgBox "This is visible while the sound is playing..."
    PlayWavFile "c:\foldername\soundfilename.wav", True
    MsgBox "This is visible after the sound is finished playing..."
End Sub

Comments

  1. I have tried in my excel and getting an error as "Constants, Fixed length strings,arrays, user-defined types and declare statements not allowed as public members of object modules"

    How can I overcome on this

Leave a Reply

Your email address will not be published. Required fields are marked *

Terms and Conditions of use

The applications/code on this site are distributed as is and without warranties or liability. In no event shall the owner of the copyrights, or the authors of the applications/code be liable for any loss of profit, any problems or any damage resulting from the use or evaluation of the applications/code.