|
今天,找到了一段能够把字符串ANSI编码与utf8编码互转的函数代码,加工了一下,使之兼容64位和32位的VBA环境,现分享给寻找它的人。
- #If Win64 And VBA7 Then
- Private Declare PtrSafe Function MultiByteToWideChar Lib "kernel32 " (ByVal CodePage As Long, ByVal dwFlags As Long, ByVal lpMultiByteStr As LongPtr, ByVal cchMultiByte As Long, ByVal lpWideCharStr As LongPtr, ByVal cchWideChar As Long) As Long
- Private Declare PtrSafe Function WideCharToMultiByte Lib "kernel32 " (ByVal CodePage As Long, ByVal dwFlags As Long, ByVal lpWideCharStr As LongPtr, ByVal cchWideChar As Long, ByVal lpMultiByteStrPtr As LongPtr, ByVal cchMultiByte As Long, ByVal lpDefaultChar As LongPtr, ByVal lpUsedDefaultChar As LongPtr) As Long
- #Else
- Private Declare Function MultiByteToWideChar Lib "kernel32 " (ByVal CodePage As Long, ByVal dwFlags As Long, ByVal lpMultiByteStr As Long, ByVal cchMultiByte As Long, ByVal lpWideCharStr As Long, ByVal cchWideChar As Long) As Long
- Private Declare Function WideCharToMultiByte Lib "kernel32 " (ByVal CodePage As Long, ByVal dwFlags As Long, ByVal lpWideCharStr As Long, ByVal cchWideChar As Long, ByVal lpMultiByteStr As Long, ByVal cchMultiByte As Long, ByVal lpDefaultChar As Long, ByVal lpUsedDefaultChar As Long) As Long
- #End If
- Private Const CP_ACP = 0 ' default to ANSI code page
- Private Const CP_UTF8 = 65001 ' default to UTF-8 code page
- '字符转 UTF8
- Public Function EncodeToBytes(ByVal sData As String) As Byte() ' Note: Len(sData) > 0
- Dim aRetn() As Byte
- Dim nSize As Long
- nSize = WideCharToMultiByte(CP_UTF8, 0, StrPtr(sData), -1, 0, 0, 0, 0) - 1
- If nSize = 0 Then Exit Function
- ReDim aRetn(0 To nSize - 1) As Byte
- WideCharToMultiByte CP_UTF8, 0, StrPtr(sData), -1, VarPtr(aRetn(0)), nSize, 0, 0
- EncodeToBytes = aRetn
- Erase aRetn
- End Function
- ' UTF8 转字符
- Public Function DecodeToBytes(ByVal sData As String) As Byte() ' Note: Len(sData) > 0
- Dim aRetn() As Byte
- Dim nSize As Long
- nSize = MultiByteToWideChar(CP_UTF8, 0, StrPtr(sData), -1, 0, 0) - 1
- If nSize = 0 Then Exit Function
- ReDim aRetn(0 To 2 * nSize - 1) As Byte
- MultiByteToWideChar CP_UTF8, 0, StrPtr(sData), -1, VarPtr(aRetn(0)), nSize
- DecodeToBytes = aRetn
- Erase aRetn
- End Function
- Sub CommandButton1_Click()
- Dim s As String
- s = StrConv(EncodeToBytes("中文"), vbUnicode) '将utf编码的数组转VB可处理字符
- MsgBox s
- t = DecodeToBytes(StrConv(s, vbFromUnicode))
- MsgBox t
- End Sub
复制代码
ANSI与Utf8编码互转.rar
(19.39 KB, 下载次数: 285)
补充内容 (2022-12-12 06:10):
更新到9楼 |
评分
-
6
查看全部评分
-
|