如何使用VBA播放波形文件或声音文件

use*_*679 8 vba

我有一个我想用VBA播放的wave文件.请帮我创建一个按钮,单击该按钮播放波形文件.

Jer*_*ire 12

这是WAV文件的一种方式.将**此代码**放在常规代码模块中:

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
Run Code Online (Sandbox Code Playgroud)

现在,您可以通过调用上面的例程并输入/ Media文件夹中找到的任何文件名,通过任何其他宏播放任何wav文件:

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
Run Code Online (Sandbox Code Playgroud)

玩弄它.

这是一个示例文件,我用它来显着地显示当天的随机名称和任务,它附加到一个按钮,就像你打算做的那样:

带有AUDIO显示的随机任务列表