在Excel中播放声音取决于button的值
VBA是不是我的实力,但我想获得一个Excel表,其中A1可能包含单词“你好”或“世界”或数字1,并根据该内容声音文件应播放时,单击button是在它的旁边。 wav文件位于excel文件所在的特定子文件夹中。
我正在使用Excel(64位)版本。 我已经在检查此页面: 如何使用VBA播放波形文件或声音文件
并尝试以下(64位兼容):
Option Explicit #If VBA7 Then Public Declare PtrSafe Function sndPlaySound32 Lib "winmm.dll" _ Alias "sndPlaySoundA" (ByVal lpszName As String, _ ByVal hModule As Long, ByVal dwFlags As Long) As Long #Else Public Declare Function sndPlaySound32 Lib "winmm.dll" _ Alias "sndPlaySoundA" (ByVal lpszName As String, _ ByVal hModule As Long, ByVal dwFlags As Long) As Long #End If 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 Sub PlayIt() Select Case Range("A1").Value Case "Hello" PlayTheSound "chimes.wav" Case "World" PlayTheSound "chord.wav" Case 1 PlayTheSound "tada.wav" End Select End Sub
但是,我得到一个错误
参数不是可选的
任何人都可以帮助我吗?
这个错误是由于你在函数期望3时用2个参数调用函数造成的。如果你想这样调用sndPlaySound32
sndPlaySound32 WhatSound, 0& ' Finally, play the sound.
那么你需要你需要改变函数签名,只有你引用的每个问题的2个参数 – 像这样:
#If VBA7 Then Public Declare PtrSafe Function sndPlaySound32 Lib "winmm.dll" _ Alias "sndPlaySoundA" (ByVal lpszName As String, ByVal dwFlags As Long) As Long #Else Public Declare Function sndPlaySound32 Lib "winmm.dll" _ Alias "sndPlaySoundA" (ByVal lpszName As String, ByVal dwFlags As Long) As Long #End If
所以完整的工作代码是:
Option Explicit #If VBA7 Then Public Declare PtrSafe Function sndPlaySound32 Lib "winmm.dll" _ Alias "sndPlaySoundA" (ByVal lpszName As String, ByVal dwFlags As Long) As Long #Else Public Declare Function sndPlaySound32 Lib "winmm.dll" _ Alias "sndPlaySoundA" (ByVal lpszName As String, ByVal dwFlags As Long) As Long #End If 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 Sub PlayIt() Select Case Range("A1").Value Case "Hello" PlayTheSound "chimes.wav" 'PlayTheSound "chime.wav" 'Case "World" 'PlayTheSound "chord.wav" 'Case 1 'PlayTheSound "tada.wav" End Select End Sub