【问题标题】:Declare Function to Play Sound in a UserForm [closed]声明在用户窗体中播放声音的函数[关闭]
【发布时间】:2019-04-22 00:52:15
【问题描述】:

好的,所以我有一个 Excel 工具,它可以打开一个用户表单,并可以选择根据选择播放声音并要求用户选择音源。这在 32 位中运行良好,但我最近更新到 64 位并了解到代码并不完全相同。

我的原始代码是这样的,位于用户窗体上的任何 Subs 之外(一般声明):

    Declare Function PlaySound Lib "winmm.dll" _
      Alias "PlaySoundA" (ByVal lpszName As String, _
      ByVal hModule As Long, ByVal dwFlags As Long) As Long

我一直在网上四处寻找,看到很多关于 PtrSafe 函数和变量作为 LongPtr 的东西,所以我尝试根据我在网上看到的示例使用这段代码:

#If VBA7 And Win64 Then
Declare PtrSafe Function PlaySound Lib "winmm.dll" _
  Alias "PlaySoundA" (ByVal lpszName As StrPtr, _
  ByVal hModule As LongPtr, ByVal dwFlags As LongPtr) As LongPtr
#Else
Declare Function PlaySound Lib "winmm.dll" _
  Alias "PlaySoundA" (ByVal lpszName As String, _
  ByVal hModule As Long, ByVal dwFlags As Long) As Long
#End If

我得到的错误是“编译错误:未定义用户定义的类型”,它突出显示#If VBA7 And Win64 Then...下的这部分代码...

Declare PtrSafe Function PlaySound Lib "winmm.dll" _
  Alias "PlaySoundA" (ByVal lpszName As StrPtr, _
  ByVal hModule As LongPtr, ByVal dwFlags As LongPtr) As LongPtr

我完全不知所措。是否有我不知道的参考资料需要核对?当其他人使用该工具时,这会导致兼容性问题吗?任何帮助表示赞赏。

【问题讨论】:

    标签: excel vba 32bit-64bit function-declaration


    【解决方案1】:

    StrPtr 是一个函数,而不是数据类型。您只需要:

    #If VBA7 Then
    Private Declare PtrSafe Function PlaySound Lib "winmm.dll" _
      Alias "PlaySoundA" (ByVal lpszName As String, _
      ByVal hModule As LongPtr, ByVal dwFlags As Long) As Long
    #Else
    Private Declare Function PlaySound Lib "winmm.dll" _
      Alias "PlaySoundA" (ByVal lpszName As String, _
      ByVal hModule As Long, ByVal dwFlags As Long) As Long
    #End If
    

    【讨论】:

    • 我实际上也尝试过该代码,但我得到一个不同的错误:“编译错误:常量、固定长度字符串、数组、用户定义类型和声明语句不允许作为对象的公共成员模块。”我认为这可能与代码位于用户窗体内的事实有关,但我尝试将它放在工作簿代码的公共空间并得到同样的问题。当它在工作簿代码中时,它实际上甚至不会让我保存。
    • @Reece 您应该能够在您的两个Declare Function 语句中更改为Private Declare ...
    • 解决了这个问题,并在 32 位和 64 位上进行了测试。我已经编辑了答案,将 Private 作为 Declare 语句的一部分。
    猜你喜欢
    • 1970-01-01
    • 2012-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多