如何在VBA中将.txt保存为Unicode或UTF-8

时间:2015-06-19 08:04:03

标签: vba excel-vba unicode utf-8 excel

我希望我的所有文件都以unicode或utf-8格式保存,而不是ANSI。

以下是代码:

Sub cvelle()
Dim iRow As Long
Dim iFile As Integer
Dim sPath As String
Dim sFile As String


For iRow = 1 To Cells(Rows.Count, "B").End(xlUp).Row
    iFile = FreeFile
    With Rows(iRow)
        sPath = "E:\" & .Range("B1").Value & "\"
        If Len(Dir(sPath, vbDirectory)) = 0 Then MkDir sPath
        sFile = .Range("D1").Value & ".txt"

        Open sPath & sFile For Output As #iFile
        Print #iFile, .Range("E1").Value
        Close #iFile
    End With
Next iRow
End Sub

现在,我认为只需插入下面的代码即可。

sFile = .Range("D1").Value & ".txt",FileFormat:= _xlUnicodeText

但它给了我一个错误。

任何建议都非常感谢。感谢。

5 个答案:

答案 0 :(得分:0)

我没有输入一堆代码,而是想出如下默认编码unicode:

 1. Right click -> New -> Text Document 
 2. Open "New Text Document.txt". Do NOT type anything! 
 3. Go to "File -> Save As... " and choose UniCode under "Encoding:", press     "Save" and overwrite existing file. Close the file. 
 4. Rename "New Text Document.txt" to "UniCode.txt" 
 5. Copy "UniCode.txt" to "C:\WINDOWS\SHELLNEW" 
 6. Open Regedit and Navigate to HKEY_CLASSES_ROOT\.txt\ShellNew 
 7. Right click in the right window -> New -> "String Value" and rename it to  "FileName". 
 8. Double click on "FileName" and put "UniCode.txt" into "Value Data". 
 9. press OK It's finished. 

感谢所有人!

答案 1 :(得分:0)

我知道如何创建未编码的txt文件。 也许您可以尝试将数据读取到变量中>创建未编码的txt>将数据写入txt>保存txt

Dim fso As Object, myTxtFile As ObjectSet 
   fso = CreateObject("Scripting.FileSystemObject")
   Set myTxtFile = fso.CreateTextFile(fileName:="c:\123.txt", OverWrite:=True, Unicode:=True)

答案 2 :(得分:0)

Function SaveTextToFile(ByVal txt$, ByVal filename$, Optional ByVal encoding$ = "windows-1251") As Boolean
    ' function saves text in txt in filename$
    On Error Resume Next: Err.Clear
    Select Case encoding$

        Case "windows-1251", "", "ansi"
            Set FSO = CreateObject("scripting.filesystemobject")
            Set ts = FSO.CreateTextFile(filename, True)
            ts.Write txt: ts.Close
            Set ts = Nothing: Set FSO = Nothing

        Case "utf-16", "utf-16LE"
            Set FSO = CreateObject("scripting.filesystemobject")
            Set ts = FSO.CreateTextFile(filename, True, True)
            ts.Write txt: ts.Close
            Set ts = Nothing: Set FSO = Nothing

        Case "utf-8noBOM"
            With CreateObject("ADODB.Stream")
                .Type = 2: .Charset = "utf-8": .Open
                .WriteText txt$

                Set binaryStream = CreateObject("ADODB.Stream")
                binaryStream.Type = 1: binaryStream.Mode = 3: binaryStream.Open
                .Position = 3: .CopyTo binaryStream        'Skip BOM bytes
                .flush: .Close
                binaryStream.SaveToFile filename$, 2
                binaryStream.Close
            End With

        Case Else
            With CreateObject("ADODB.Stream")
                .Type = 2: .Charset = encoding$: .Open
                .WriteText txt$
                .SaveToFile filename$, 2        ' saving in coding that you need
                .Close
            End With
    End Select
    SaveTextToFile = Err = 0: DoEvents
End Function

答案 3 :(得分:0)

我个人在工作中使用它,因为有些pl报告具有很多格式,因此要进行调整,您需要在这里使用它来读取```

Function LoadTextFromTextFile(ByVal filename$, Optional ByVal encoding$) As String
    ' functions loads in code  Charset$ from filename$
    On Error Resume Next: Dim txt$
    If Trim(encoding$) = "" Then encoding$ = "windows-1251"
    With CreateObject("ADODB.Stream")
        .Type = 2:
        If Len(encoding$) Then .Charset = encoding$
        .Open
        .LoadFromFile filename$        'load data from file 
        LoadTextFromTextFile = .ReadText        ' read text
        .Close
    End With
End Function

答案 4 :(得分:0)

希望这可以为某人节省一些时间:

Sub ExportToTxt()
    Dim fileStream As Object
    Set fileStream = CreateObject("ADODB.Stream")
    fileStream.Charset = "utf-8"
    fileStream.Open

    Dim rangeToExport As Range
    Set rangeToExport = Worksheets("BPC-Processed").Range("A1").CurrentRegion

    Dim firstCol, lastCol, firstRow, lastRow As Integer
    firstCol = rangeToExport.Columns(1).Column
    lastCol = firstCol + rangeToExport.Columns.Count - 1
    firstRow = rangeToExport.Rows(1).row
    lastRow = firstRow + rangeToExport.Rows.Count - 1

    Dim r, c As Integer
    Dim str As String
    Dim delimiter As String
    For r = firstRow To lastRow
        str = ""
        For c = firstCol To lastCol
            If c = 1 Then
                delimiter = ""
            Else
                delimiter = vbTab ' tab
            End If
            str = str & delimiter & rangeToExport.Cells(r, c).Value
        Next c
        fileStream.WriteText str & vbCrLf ' vbCrLf: linebreak
    Next r

    Dim filePath As String
    filePath = Application.ThisWorkbook.Path & "\BPC-Processed.txt"
    fileStream.SaveToFile filePath, 2 ' 2: Create Or Update
    fileStream.Close
End Sub