vba 声音

首先在模块区申明此函数,代码如下:

Public Declare Function PlaySound Lib "winmm.dll" Alias "PlaySoundA" (ByVal lpszName As String, ByVal hModule As Long, ByVal dwFlags As Long) As Long
2,然后就可以在子过程或者事件中调用了,方式如下

 Sub playS()
Call PlaySound("你要播放的声音文件,只支持wav格式", 0&, &H0) '这里的具体参数使用你可以搜一下我就不多说了。基本调用方式就这样
End Sub
Public Declare Function sndPlaySound32 _
    Lib "winmm.dll" _
    Alias "sndPlaySoundA" ( _
        ByVal lpszSoundName As String, _
        ByVal uFlags As Long) As Long
        
Public Declare Function PlaySound Lib "winmm.dll" Alias "PlaySoundA" (ByVal lpszName As String, ByVal hModule As Long, ByVal dwFlags As Long) As Long

  模块中引入函数

程序中调用函数

Call PlaySound(ThisWorkbook.Path & "抽奖图片1.wav", 0&, &H1) '这里的具体参数使用你可以搜一下我就不多说了。基本调用方式就这样

' SND_SYNC(=&H0) 同步调用,声音播放完毕 程序才能继续' SND_ASYNC(=&H1) 非同步
' SND_ASYNC(=&H1) 非同步调用,不必等声音播放完毕 程序即可继续
' SND_NODEFAULT(=&H2)当声音文件未找到就停止播音返回
' SND_MEMORY(&H4) 播放内存中的声音
' SND_LOOP(=&H8) 声音播放完毕后 从头重复播放 与SND_ASYNC(=&H1)使用
' SND_NOSTOP(=&H10) 如果其他声音正在播放 则不终止该声音的播放,而返回False
'0, &H20000 Or &H1

自定义函数

Sub PlayTheSound(ByVal WhatSound As String)
    If Dir(WhatSound, vbNormal) = "" Then
        ' WhatSound is not a file. Get the file named by
        ' WhatSound from the WindowsMedia directory.
        WhatSound = Environ("SystemRoot") & "抽奖图片" & 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
            ' Can't find the file. Do a simple Beep.
            Beep
            Exit Sub
        End If
    Else
        ' WhatSound is a file. Use it.
    End If
    ' Finally, play the sound.
    sndPlaySound32 WhatSound, 0
    
End Sub

调用

PlayTheSound "声音名字" '声音文件放在同一目录
原文地址:https://www.cnblogs.com/--3q/p/14029222.html