VBA导出UTF-8到txt

作者:追风剑情 发布于:2014-8-25 18:26 分类:VBA

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 必须在通用模块顶部

标签: VBA

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号