鸟语天空
VBA导出UTF-8到txt
post by:追风剑情 2014-8-25 18:26
Public Declare Function WideCharToMultiByte Lib "kernel32" (ByVal CodePage As Long, ByVal dwFlags As Long, ByVal lpWideCharStr As Long, ByVal cchWideChar As Long, ByRef lpMultiByteStr As Any, ByVal cchMultiByte As Long, ByVal lpDefaultChar As String, ByVal lpUsedDefaultChar As Long) As Long
Public Const CP_UTF8 = 65001
Function WriteUTF8(ByVal s, ByVal filePath) As String
    Dim strstr As String
    Dim bByte As Byte
    Dim lBufSize As Long
    Dim lRest As Long
    Dim bUTF8() As Byte
    Dim TLen As Long
    
    strstr = s
    
    TLen = Len(strstr)
    lBufSize = TLen * 3 + 1
    ReDim bUTF8(lBufSize - 1)
    lRest = WideCharToMultiByte(CP_UTF8, 0, StrPtr(strstr), TLen, bUTF8(0), lBufSize, vbNullString, 0)
    If lRest Then
        lRest = lRest - 1
        ReDim Preserve bUTF8(lRest)
        Open filePath For Binary As #1
        
        '以下被注释掉的代码是向文件头写入BOM标志
        'bByte = 239
        'Put #1, , bByte
        'bByte = 187
        'Put #1, , bByte
        'bByte = 191
        'Put #1, , bByte
        
        Put #1, , bUTF8
        Close #1
    End If
End Function
注意
Declare 必须在通用模块顶部
评论:
发表评论:
昵称

邮件地址 (选填)

个人主页 (选填)

内容