UTF8方式读写文件

发布时间:2019-09-02编辑:脚本学堂
UTF8方式读写文件

编写一个utf8方式读写文件的模块。
 

复制代码 代码如下:
Public Function SaveFile(FileName As Variant, strFileBody As Variant) As Boolean
On Error GoTo err1
    Dim ADO_Stream As Object
    Set ADO_Stream = CreateObject("ADODB.Stream")
  
    With ADO_Stream
        .Type = 2
        .Mode = 3
        .Charset = "utf-8"
        .Open
        .WriteText strFileBody
        .SaveToFile FileName, 2
    End With
  
    SaveFile = True
    Set ADO_Stream = Nothing
  
    Exit Function
err1:
    SaveFile = False
    MsgBox "write to file error!" & vbCrLf & vbCrLf & FileName, vbExclamation
End Function
Public Function ReadUTF8(ByVal sUTF8File As String) As String
     If Len(sUTF8File) = 0 Or Dir(sUTF8File) = vbNullString Then Exit Function
     Dim ados As Object
     Set ados = CreateObject("ADODB.Stream")
     With ados
         .Charset = "utf-8"
         .Type = 2
         .Open
         .LoadFromFile sUTF8File
         ReadUTF8 = .ReadText
         .Close
     End With
     Set ados = Nothing
End Function