VBA 将 ANSI 转换为 UTF-8文件

在使用的时候,先用WriteOut生成一个临时文件(UTF-8带BOM),
然后用Convert2utf8将BOM头的前三个字节删除。

----------------------------------------------------------

Private Sub WriteOut(strPath As String, str As String) 
    Dim objStream As Object
    Set objStream = CreateObject("ADODB.Stream") 
    With objStream
        .Type = 2               'adTypeText
        .Charset = "UTF-8"
        .Open
        .WriteText str
        .SaveToFile strPath, 2  'adSaveCreateOverWrite
    End With 
    Set objStream = Nothing
End Sub


Public Function Convert2utf8(fileName As String, FileTo As String) As Boolean
 
    Dim ReadIntFileNum, WriteIntFileNum As Integer
    ReadIntFileNum = FreeFile() '获取一个空文件
    WriteIntFileNum = FreeFile() + 1
     
    Open fileName For Binary As ReadIntFileNum
    Open FileTo For Binary As #WriteIntFileNum
'    Dim byteFrom, byteTo As String
    Dim fileByte As Long
    Seek #ReadIntFileNum, 4
   
    While Not EOF(ReadIntFileNum)
    
        Get #ReadIntFileNum, , fileByte
        Put #WriteIntFileNum, , fileByte
    Wend
    
    Close #ReadIntFileNum
    Close #WriteIntFileNum
    Kill fileName
End Function

posted on 2014-06-17 11:57  sodo  阅读(2228)  评论(0编辑  收藏  举报

导航