VBA產生或讀取指定字元集的文字檔

來源:互聯網
上載者:User
用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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.