VB&VBA/VBScript读取和保存UTF-8文件方案

=============================== VB&VBA Code ===============================

 

 

Public Function SaveFile(FileName As Variant, strFileBody As Variant) As Boolean

 

    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
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

 

 

=============================== VBScript Code ===============================

Function LoadFile(Path)
        Dim Stm2
        Set Stm2 = CreateObject("ADODB.Stream")
        Stm2.Type = 2
        Stm2.Mode = 3
        Stm2.Open

        Stm2.LoadFromFile Path
        Stm2.Charset = "UTF-8"
        'Stm2.Charset = "Unicode"
        'Stm2.Charset = "GB2312"
        
        Stm2.position = 0
        LoadFile = Stm2.ReadText
        Stm2.Close
        Set Stm2 = nothing
    End Function


    Function WriteToFile(file, Message)
        
        Dim Stm1
        Set Stm1 = CreateObject("ADODB.Stream")
        Stm1.Type = 2
        Stm1.Open
        Stm1.Charset = "UTF-8"
        'Stm1.Charset = "Unicode"
        Stm1.Position = Stm1.Size
        
        Stm1.WriteText LoadFile(file) + vbCrLf + Message
      
        Stm1.SaveToFile file,2
        Stm1.Close
        set Stm1 = nothing
    End Function

转自https://www.cnblogs.com/Waver/archive/2008/09/04/1283842.html

你可能感兴趣的:(VBA)