VB字符与 UTF8格式互转

在VB模块文件中加入下面代码:

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
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
Private Sub Command1_Click()
Dim s As String
s = StrConv(EncodeToBytes("中文"), vbUnicode) '将utf编码的数组转VB可处理字符
MsgBox s
t = DecodeToBytes(StrConv(s, vbFromUnicode))
MsgBox t
End Sub

'

使用方法:
1、utf8转VB字符串

    Private Sub Utf8ToVBstr_Click()
        Dim vbstr As String
        vbstr  = DecodeToBytes(StrConv(这里填待转换的utf8字符串, vbFromUnicode))
        MsgBox vbstr 
    End Sub

2、VB字符串转utf8

Private Sub VBstrToUtf8_Click()
    Dim utf8str As String
	utf8str =EncodeToBytes(这里填待转换的VB字符串);
    MsgBox utf8str 
End Sub

你可能感兴趣的:(VB)