字体编码有ansi 和Unicode等,不同环境默认字体编码方式不同,转换代码如下:
'Option Explicit
Function ReadTextByChatSet(FileName, Optional CharSet = "UTF-8")
'读文件 根据文本编码格式
Dim oStream As Object
Dim sText As String
Set oStream = CreateObject("ADODB.Stream")
oStream.Open
oStream.CharSet = CharSet 'unicode|utf-8;Ascii; gb2312; big5; gbk
oStream.Type = 2 'adTypeText
oStream.LoadFromFile FileName
ReadTextByChatSet = oStream.ReadText()
oStream.Close
Set oStream = Nothing
End Function
'函数名称:WriteToTextFile
'作用:利用Adodb.Stream对象来写入UTF-8编码的文件
'示例:Call WriteToTextFile("File/FileName.htm",Content,"UTF-8")
Sub WriteToTextFile(FilePath, ByVal str, Optional CharSet = "Ascii", Optional bak = False)
Dim stm
Set stm = CreateObject("adodb.stream")
stm.Type = 2 '2-文本模式读取,1-二进制模式
stm.Mode = 3 '3-读写,1-读,2-写
stm.CharSet = CharSet 'UNICODE|UTF-8;Ascii; gb2312; big5; gbk;
stm.Open
stm.WriteText str
If Dir(FilePath) <> "" Then '文件存在备份后覆盖
If bak Then FileCopy FilePath, FilePath & Format(Now, "-yymmdd_hhmm") '备份文件
stm.SaveToFile FilePath, 2 '2可省略,adSaveCreateNotExist =1 , adSaveCreateOverWrite =2
Else
stm.SaveToFile FilePath, 1 '不存在则创建文件
End If
stm.Flush
stm.Close
Set stm = Nothing
End Sub