VBA中播放声音

分类:代码, 博客 标签:

VBA中我们需要定时或者输入错误时播放声音来给用户进行提示,这是一个比较有用的功能,这里给出一段比较有效的代码,它调用了”winmm.dll”中的sndPlaySoundA函数:

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
            ' 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 "chord"
'等价于
PlayTheSound "C:\Windows\Media\Chord.wav"


分类:代码, 博客 标签:

发表评论

You must be logged in to post a comment.