VBA生成或读取指定字符集的文本文件
用VBA做工具的过程中,遇见这样一个问题。使用FSO方式或者直接OPEN文件方式,生成的文本文件采用的字符集为当前操作系统默认字符集,不能选择字符集类型。这样的文件作为应用程序的配置文件或者作为js代码文件,常常会因为字符集不是UTF-8,不能直接使用,需要利用记事本进行一次人工的字符集转换。特别麻烦。
近日发现有一办法,可以较好的解决这个问题。即是采用ADO的方式,将字符串生成以指定字符集的流文件输出。
函数代码如下,VB或VBA中均可用。注意:需要添加对ADO 对象库的引用。
ADO方式写入
'功能:text保存为文件(ADO方式)
'输入:输出文件地址、内容文本、字符集
'输出:无
Sub WriteToTextFileADO(filePath As String, strContent As String, CharSet As String)
Set stm = New ADODB.Stream
stm.Type = 2 '以本模式读取
stm.Mode = 3
stm.CharSet = CharSet
stm.Open
stm.WriteText strContent
'如果文件存在,删除文件
If Len(Dir(filePath)) > 0 Then
Kill filePath
End If
stm.SaveToFile filePath, 2
stm.Flush
stm.Close
Set stm = Nothing
End Sub
使用示例:
Call WriteToTextFileADO(Sheets("channel-list").Cells(3, 5) & "\" & feedName & ".xml", feedXml, "utf-8")
'功能:读取text文件(ADO方式)
'输入:输入文件地址、字符集
'输出:无
Function ReadFromFileADO(filePath As String, CharSet As String) As String
Dim strRtn As String
Set stm = New ADODB.Stream
stm.Type = 2 '以本模式读取
stm.Mode = 3
stm.CharSet = CharSet
stm.Open
stm.LoadFromFile filePath
strRtn = stm.ReadText
stm.Close
Set stm = Nothing
ReadFromFileADO = strRtn
End Function
近日发现有一办法,可以较好的解决这个问题。即是采用ADO的方式,将字符串生成以指定字符集的流文件输出。
函数代码如下,VB或VBA中均可用。注意:需要添加对ADO 对象库的引用。
ADO方式写入
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
使用示例:
![](/Images/OutliningIndicators/None.gif)
ADO方式读取
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)