用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")
ADO方式讀取
'功能:讀取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