How to play a wave file or sound file using VBA

I have a wave file that I want to play using VBA. Please help me create a button that when I click on play the wave file.

+5
source share
1 answer

Here is a way for wav files. Put ** this code ** in a regular code module:

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

Sub PlayTheSound(ByVal WhatSound As String)
    If Dir(WhatSound, vbNormal) = "" Then
        ' WhatSound is not a file. Get the file named by
        ' WhatSound from the Windows\Media directory.
        WhatSound = Environ("SystemRoot") & "\Media\" & WhatSound
        If InStr(1, WhatSound, ".") = 0 Then
            ' if WhatSound does not have a .wav extension,
            ' add one.
            WhatSound = WhatSound & ".wav"
        End If
        If Dir(WhatSound, vbNormal) = vbNullString Then
            Beep            ' Can't find the file. Do a simple Beep.
            Exit Sub
        End If
    Else
        ' WhatSound is a file. Use it.
    End If

    sndPlaySound32 WhatSound, 0&    ' Finally, play the sound.
End Sub

Now you can play any wav file through any other macro, calling this procedure above and submitting any file name located in the / Media folder:

Sub PlayIt()
    Select Case Range("A1").Value
        Case "good"
            PlayTheSound "chimes.wav"
        Case "bad"
            PlayTheSound "chord.wav"
        Case "great"
            PlayTheSound "tada.wav"
    End Select
End Sub

Play with it.

Here is an example file in which I use this to sharply identify random names and tasks during the day, it is attached to the button as you plan:

Random task list with AUDIO indicator

+11

All Articles