VBA不是我的优势,但我想获得一张Excel表格,其中A1可能包含单词“Hello”或“World”或数字1,并且根据该内容,单击时应播放声音文件旁边的按钮。 wav文件位于excel文件所在的特定子文件夹中。
我正在使用Excel(64位)版本。我已经在查看此页面了: How to play a wave file or sound file using 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
然而,我收到了错误
参数不是可选的
任何人都可以帮助我吗?
答案 0 :(得分:1)
导致错误是因为当函数需要3时调用带有2个参数的函数。如果你想这样调用sndPlaySound32
sndPlaySound32 WhatSound, 0& ' Finally, play the sound.
然后你需要根据referenced的问题更改函数签名,使其只有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