VBA Excel WideCharToMultiByte Compile error on 64-bit System
Compile Error:
The code in this project must be updated for use on64-bit systems.
Please review and update Declare statements and then mark them with the PtrSafe attribute.
1.问题:
32-bit的VBA程序,在64-bit系统上运行时,出现该编译错误。
环境:Office2010 Excel 64-bit, 64-bit Win7 OS
2.原因
原程序中,函数声明如下。该函数在32-bit系统中编译、运行没有问题。但是在64-bit系统中会出现编译错误。
Private Declare Function WideCharToMultiByte Lib "kernel32" _
(ByVal CodePage As Long, ByVal dwFlags As Long, lpWideCharStr As Integer, ByVal cchWideChar As Long, _
lpMultiByteStr As Byte, ByVal cchMultiByte As Long, ByVal lpDefaultChar As String, ByVal lpUsedDefaultChar As Long) As Long
3.修改
其实,提示信息中,已经说明的很清楚了。
只要在函数的声明处添加"PtrSafe"属性(无需修改其他地方),程序就正常了。
修改后程序:
Private Declare PtrSafe Function WideCharToMultiByte Lib "kernel32" _
(ByVal CodePage As Long, ByVal dwFlags As Long, lpWideCharStr As Integer, ByVal cchWideChar As Long, _
lpMultiByteStr As Byte, ByVal cchMultiByte As Long, ByVal lpDefaultChar As String, ByVal lpUsedDefaultChar As Long) As Long
4.扩展
①PtrSafe<Keyword>
https://msdn.microsoft.com/en-us/library/office/gg278832.aspx?f=255&MSPPError=-2147217396
Declare statements with the PtrSafe keyword is the recommended syntax. Declare statements that include PtrSafe work correctly in the VBA7 development environment on both 32-bit and 64-bit platforms only after all data types in the Declare statement (parameters and return values) that need to store 64-bit quantities are updated to use LongLong for 64-bit integrals or LongPtr for pointers and handles. To ensure backwards compatibility with VBA version 6 and earlier use the following construct:
②LongPtr Data Type
https://msdn.microsoft.com/en-us/library/office/gg251378.aspx?f=255&MSPPError=-2147217396
LongPtr (Long integer on 32-bit systems, LongLong integer on 64-bit systems) variables are stored as signed 32-bit (4-byte) numbers ranging in value from -2,147,483,648 to 2,147,483,647 on 32-bit systems; and signed 64-bit (8-byte) numbers ranging in value from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 on 64-bit systems.