VBA导出UTF-8到txt

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

  1. 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
  2. Public Const CP_UTF8 = 65001
  3. Function WriteUTF8(ByVal s, ByVal filePath) As String
  4.     Dim strstr As String
  5.     Dim bByte As Byte
  6.     Dim lBufSize As Long
  7.     Dim lRest As Long
  8.     Dim bUTF8() As Byte
  9.     Dim TLen As Long
  10.     
  11.     strstr = s
  12.     
  13.     TLen = Len(strstr)
  14.     lBufSize = TLen * 3 + 1
  15.     ReDim bUTF8(lBufSize - 1)
  16.     lRest = WideCharToMultiByte(CP_UTF8, 0, StrPtr(strstr), TLen, bUTF8(0), lBufSize, vbNullString, 0)
  17.     If lRest Then
  18.         lRest = lRest - 1
  19.         ReDim Preserve bUTF8(lRest)
  20.         Open filePath For Binary As #1
  21.         
  22.         '以下被注释掉的代码是向文件头写入BOM标志
  23.         'bByte = 239
  24.         'Put #1, , bByte
  25.         'bByte = 187
  26.         'Put #1, , bByte
  27.         'bByte = 191
  28.         'Put #1, , bByte
  29.         
  30.         Put #1, , bUTF8
  31.         Close #1
  32.     End If
  33. End Function
  1. 注意
    1. Declare 必须在通用模块顶部

标签: VBA

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号