【问题标题】:How to use Windows SHBrowseforFolder function on 32 bit or 64 bit Excel VBA如何在 32 位或 64 位 Excel VBA 上使用 Windows SHBrowseforFolder 函数
【发布时间】:2021-07-26 11:18:07
【问题描述】:

我有一个模块(“Module1.bas”),其中使用条件编译常量作为编程测试来确定 VBA 版本号(例如 VBA7)以及它是否在 64 位平台上运行。根据该测试的结果,私有类型“BROWSEINFO”被声明为 Windows API 函数 SHBrowseforFolder,它在 32 位和 64 位类型之间变化。在 32 位版本中它返回一个 Long,而在 64 位版本中它返回一个 LongPtr。

效果很好。

但是,在同一个模块中,有一个函数“GetDirectory”,它使用上述声明中的数据类型和 SHBrowseforFolder 函数....除此函数外,返回类型在 GetDirectory 的开头声明功能为 Long ,因此被“硬编码”。似乎没有任何方法可以使这些数据类型以 VBA 版本和操作系统类型为条​​件。

我错过了什么吗?

我真的希望能够根据运行 VBA 的 Excel 版本来运行 VBA,而不是拥有 2 个不同的版本。

【问题讨论】:

  • 您能否复制您的函数,一个用于 32 位,一个用于 64 位,并使用 If...Then 语句来建立 If 32bit Excel Then Do the 32bit function... 等?
  • 请向我们展示能够重现问题的代码。
  • 感谢您的回复,但是,我能够解决问题。由于 LongPtr 类型的变量在 32 位版本的 Office 中解析为 Long,而在 64 位版本的 Office 中解析为 LongLong,我只是在 GetDirectory 函数中将这两个变量声明为 LongPtr 类型。错误就会消失(假设 Windows API 声明是 32/64 位特定的,使用条件编译常量)。

标签: excel vba


【解决方案1】:

您可以在一个代码中执行此操作 :) 只需将声明语句放在您需要的地方。

Dim bits64 As Boolean
    #If VBA7 Then
         #If Win64 Then
            bits64 = True 'excel 64 bits
         #Else
            bits64 = False
         #End If
    #Else
        bits64 = False
    #End If

第二个例子:

#If VBA7 Then
    Public Declare PtrSafe Function WritePrivateProfileString Lib "kernel32" Alias "WritePrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As Any, ByVal lpString As Any, ByVal lpFileName As String) As Long
#Else
    Public Declare Function WritePrivateProfileString Lib "kernel32" Alias "WritePrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As Any, ByVal lpString As Any, ByVal lpFileName As String) As Long
#End If

【讨论】:

  • 感谢您的回复,但是,我能够解决问题。由于 LongPtr 类型的变量在 32 位版本的 Office 中解析为 Long,而在 64 位版本的 Office 中解析为 LongLong,我只是在 GetDirectory 函数中将这两个变量声明为 LongPtr 类型。错误就会消失(假设 Windows API 声明是 32/64 位特定的,使用条件编译常量)。
  • @RobBarrow 在 Office 2010 中,微软引入了 VBA7,它包含一个真正的指针数据类型:LongPtr。这允许引用 64 位地址空间。因此,如果您在 Excel 2007 或更低版本上启动 VBA 代码,则会引发错误。这就是为什么你应该使用“#If VBA7 Then .. #Else .. #End If”并有 2 个变体。
猜你喜欢
  • 2012-10-26
  • 2019-01-07
  • 2011-05-13
  • 2017-03-26
  • 2011-10-24
  • 1970-01-01
  • 1970-01-01
  • 2012-10-25
  • 1970-01-01
相关资源
最近更新 更多