【问题标题】:How to save .txt as Unicode or UTF-8 in VBA如何在 VBA 中将 .txt 保存为 Unicode 或 UTF-8
【发布时间】:2015-06-19 08:04:03
【问题描述】:

我希望我的所有文件都保存为 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

但它给了我一个错误。

【问题讨论】:

标签: excel vba unicode utf-8


【解决方案1】:

我知道如何创建一个未编码的 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】:
    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
    

    【讨论】:

    • 如果您编辑答案以解释这是一个好的解决方案的方式和原因,将会很有帮助。
    • 要在同一页面上,主题启动器在保存我发布的通用脚本时遇到问题,该脚本可用于多种格式 koi8-r、ascii、utf-7、utf-8、utf-8noBOM、 utf-16, Windows-1251, unicode 你可以查看完整列表 HKEY_LOCAL_MACHINE\SOFTWARE\Classes\MIME\Database\Charset
    • 我的意思是不编辑答案,而不是添加评论,以便未来的读者能够理解。我是 Unicode Consortium 发表的关于恶劣环境中字符集识别的论文的作者。
    【解决方案3】:

    我个人在工作中使用它,因为一些 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】:

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

      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
      

      【讨论】:

        【解决方案5】:

        我没有输入一堆代码,而是想办法将默认编码设为 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. 
        

        谢谢大家!

        【讨论】:

        • 我们如何使用 VBA 做到这一点?(如上编辑注册表)
        • 这会强制整个系统使用其中保存有Unicode BOM 的文本文件作为shell 创建的所有纯文本文件的模板。可以说,即使对您自己的计算机,您也不应该这样做;最肯定not to other people's computers。另请注意,这并不能神奇地确保在您键入时将 Unicode 数据保存在文件中。只有可能发生如果结束程序寻找BOM。记事本可以。
        猜你喜欢
        • 2017-09-09
        • 2013-09-07
        • 1970-01-01
        • 1970-01-01
        • 2016-11-08
        • 1970-01-01
        • 2021-02-11
        • 2013-06-22
        • 2013-04-18
        相关资源
        最近更新 更多