兼容性 32 位-excel 和 64 位 excel (office 365)

compatibility 32bit-excel and 64-bit excel (office 365)

我在vba方面没有经验,所以感谢您的理解。

我在 Office 365 中测试了一些旧宏,之前我使用 excel 2016。

我了解到某些宏可能由于 Long 变量声明而无法正常工作。 - 据我正确理解 Long4bitLongLong8bit。还有像 ►LongPtr 这样的东西,它有 4 位 -当不是 VBA7 和 8 位 -在 VBA7 中。

我的问题如下:怎么可能在excel365中我仍然可以使用普通的Long变量?

Long 数据类型没有死

I read that some macros might not work properly because of the Long variable declaration.

您可能指的是使用 API 函数 (API - 应用程序编程接口)您必须 照顾不同的环境。这些系统函数do需求 LongPtr 类型用于 指针 句柄 或 → 内存位置 (注意特殊 PtrSafe 前缀!)。

My question is as follows: how it is possible that in excel365 I can still use normal Long variable?

一个 VBA 过程,与引用的 API 函数相反 不会强制“禁止”变量的 Long 数据类型, 就像你在没有 Integer 的情况下被迫做的一样少(虽然内部 VBA 更喜欢 Long 整数 )。

LongPtr 声明的进一步说明

因为 window 句柄在 Office 2010 或更高版本中声明为 LongPtrLong之前的版本一样,需要区分不同的版本 通过条件编译常量 (#If VBA7 Then .. #End If) ,例如

#If VBA7 Then              ' Office 2010 or higher
    Private Declare PtrSafe Function FindWindow Lib "User32" Alias "FindWindowA" _
           (ByVal lpClassName As String, _
            ByVal lpWindowName As String) _
    As LongPtr  
#Else
    Private Declare Function FindWindow Lib "User32" _
        Alias "FindWindowA" _
       (ByVal lpClassName As String, _
        ByVal lpWindowName As String) As Long
#End If

请注意,某些 API 函数还需要使用条件 Win64 常量来识别实际安装的 64 位 Office 系统; 我已经提到过,默认情况下,Office 经常安装为 32 位。

LongPtr,但这不是真正的数据类型,因为它转换为正确的数据类型 视实际32/64位环境而定。

请注意,64 位系统可以安装为 32 位 office 或 64 位 office。 LongPtr 允许编写可以在 32 位和 64 位环境中 运行 的可移植代码。

提示:注意声明分配的 API 变量以及适当的数据类型。 如果您通过 条件编译常量 区分版本,则必须 对您自己的程序中的引用变量也这样做。

相关链接

进一步推荐阅读 (thx @GSerg :-)

在以下帖子中引用@GSerg:

"By adding PtrSafe to a function declaration, you promise to the compiler that you have put LongPtr in all places where it needs to be, and nowhere else."

"LongPtr is a pointer-sized integer. It must be used for things that have the same size as a pointer."

"Long exists in all versions and means the same thing in all versions (32-bit integer). You should not change it to LongPtr for the sake of it. You should only use LongPtr for pointers or pointer-sized data types."