如何在UTF-8中将行保存到文件?

时间:2019-05-19 19:10:58

标签: excel vba

我正在尝试将大型txt文件拆分为多个txt文件(编码UTF-8)。我正在使用的语言是亚洲语言。

我尝试了一些VBA和Python代码,但无法完成这项工作。

Sub ExportTextFiles()

Dim i As Long
Dim LastDataRow As Long
Dim MyFile As String
Dim fnum


    LastDataRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row
    For i = 1 To LastDataRow
        'The next line uses the contents of column A on the same row to name it
        MyFile = "C:\Users\grego\Downloads\" & ActiveSheet.Range("A" & i).Value & ".txt"
        'Use the following line instead to just create a series of numbered files
        'MyFileName = "C:\Users\grego\Downloads\" & i & ".txt"
        fnum = FreeFile()
        Open MyFile For Output As fnum
        Print #fnum, Format(Range("B" & i))
        Close fnum
    Next i

End Sub

此宏运行良好,但输出为ANSI,而不是Unicode,但出现了问号字符串。任何帮助将非常感激!我也可以使用一些python。

1 个答案:

答案 0 :(得分:1)

您可以使用ADO-Stream对象来读写utf-8文件。

Public Function ReadUTF8(f As String) As String
    Dim st As Object
    Set st = CreateObject("ADODB.Stream")
    st.Charset = "utf-8"
    st.Open
    st.LoadFromFile f
    ReadUTF8 = st.ReadText
    st.Close
    Set st = Nothing
End Function

Public Sub WriteUTF8(f As String, content As String)
    Const adSaveCreateOverWrite = 2
    Dim st As Object
    Set st = CreateObject("ADODB.Stream")
    st.Charset = "utf-8"
    st.Open
    st.WriteText content
    st.SaveToFile f, adSaveCreateOverWrite
    st.Close
    Set st = Nothing
End Sub

然后,您只需要在循环内使用它即可

MyFile = "C:\Users\grego\Downloads\" & ActiveSheet.Range("A" & i).Value & ".txt"
WriteUTF8 MyFile, ActiveSheet.Range("B" & i).Text