【发布时间】:2014-02-24 08:40:19
【问题描述】:
我应该找出 64 位系统上 excel VBA 代码兼容性的问题。我不使用 VB 语言,下面的代码不是我的,但我必须解决这个问题。
Excel VB 代码:
Option Explicit
Private Declare Function WideCharToMultiByte Lib "kernel32.dll" (ByVal CodePage As Long, ByVal dwFlags As Long, ByVal lpWideCharStr As Long, ByVal cchWideChar As Long, ByRef lpMultiByteStr As Byte, ByVal cchMultiByte As Long, ByVal lpDefaultChar As String, ByRef lpUsedDefaultChar As Long) As Long
Private Const CP_UTF8 As Long = 65001
Private Const ERROR_INSUFFICIENT_BUFFER As Long = 122&
Public Function ToUTF8(s As String) As Byte()
If Len(s) = 0 Then Exit Function
Dim ccb As Long
ccb = WideCharToMultiByte(CP_UTF8, 0, StrPtr(s), Len(s), ByVal 0&, 0, vbNullString, ByVal 0&)
If ccb = 0 Then
Err.Raise 5, , "Internal error."
End If
Dim b() As Byte
ReDim b(1 To ccb)
If WideCharToMultiByte(CP_UTF8, 0, StrPtr(s), Len(s), b(LBound(b)), ccb, vbNullString, ByVal 0&) = 0 Then
Err.Raise 5, , "Internal error."
Else
ToUTF8 = b
End If
End Function
我已尝试将条件 #If VBA7 和 PtrSave 添加到任何地方,但工作表仍然不起作用。
这是我在 Office 64 位中尝试过的代码
Option Explicit
#If VBA7 Then
Private Declare PtrSafe Function WideCharToMultiByte Lib "kernel32" (ByVal CodePage As Integer, ByVal dwFlags As Long, ByVal lpWideCharStr As LongPtr, ByVal cchWideChar As Long, ByVal lpMultiByteStr As Long, ByVal cchMultiByte As LongPtr, ByVal lpDefaultChar As Long, ByVal lpUsedDefaultChar As Long) As LongPtr
#Else
Private Declare Function WideCharToMultiByte Lib "kernel32.dll" (ByVal CodePage As Long, ByVal dwFlags As Long, ByVal lpWideCharStr As Long, ByVal cchWideChar As Long, ByRef lpMultiByteStr As Byte, ByVal cchMultiByte As Long, ByVal lpDefaultChar As String, ByRef lpUsedDefaultChar As Long) As Long
#EndIf
Private Const CP_UTF8 As Long = 65001
Private Const ERROR_INSUFFICIENT_BUFFER As Long = 122&
Public Function ToUTF8(s As String) As Byte()
If Len(s) = 0 Then Exit Function
Dim ccb As LongPtr
ccb = WideCharToMultiByte(CP_UTF8, 0, StrPtr(s), Len(s), ByVal 0&, 0, vbNullString, ByVal 0&)
If ccb = 0 Then
Err.Raise 5, , "Internal error."
End If
Dim b() As Byte
ReDim b(1 To ccb) // ERROR TYPE MISMATCH on ccb
If WideCharToMultiByte(CP_UTF8, 0, StrPtr(s), Len(s), b(LBound(b)), ccb, vbNullString, ByVal 0&) = 0 Then
Err.Raise 5, , "Internal error."
Else
ToUTF8 = b
End If
End Function
感谢您的帮助。
【问题讨论】:
-
此代码不适用于 Office 64 位,因为您需要更改 API 声明。请参阅THIS 链接。
I have tried to add conditions #If VBA7 and PtrSave to everywhere but woksheet still does not work您能告诉我们您在 64 位 Office 中尝试过的确切代码吗? -
当我在 excel 中调试上面的代码时,我会在这部分“ReDim b(1 To ccb)”中收到错误消息“TYPE MISMATCH”...
-
在我将 LongPtr 类型更改为 Long 之后,此行出现错误“类型不匹配”(程序突出显示函数名称):ccb = WideCharToMultiByte(CP_UTF8, 0, StrPtr(s), Len(s), ByVal 0&, 0, vbNullString, ByVal 0&)
-
还是一样的错误“类型不匹配”(程序高亮函数名)
-
您进行了第四次更改吗?当您回复时,我正在编辑帖子。您可能需要刷新页面才能看到它