如何导出使用“Unicode”编码的CSV文件

目前我使用VBA代码将范围数据导出到CSV文件:

Sub Fct_Export_CSV_Migration() Dim Value As String Dim size As Integer Value = ThisWorkbook.Path & "\Export_Migration" & Sheets(1).range("B20").Value & ".csv" chemincsv = Value Worksheets("Correspondance Nv Arborescence").Select Dim Plage As Object, oL As Object, oC As Object, Tmp As String, Sep$ Sep = ";" size = Worksheets("Correspondance Nv Arborescence").range("B" & Rows.Count).End(xlUp).Row Set Plage = ActiveSheet.range("A1:B" & size) Open chemincsv For Output As #1 For Each oL In Plage.Rows Tmp = "" For Each oC In oL.Cells Tmp = Tmp & CStr(oC.Text) & Sep Next 'take one less than length of the string number of characters from left, that would eliminate the trailing semicolon Tmp = Left(Tmp, Len(Tmp) - 1) Print #1, Tmp Next Close MsgBox "OK! Export to " & Value End Sub 

现在,我想导出用“ Unicode ”编码的CSV。 我想我需要使用像SaveAs(xlUnicodeText)的VBAfunction,但如何使用它?

谢谢

Unicode CSVs不是Excel支持的文件格式之一。 这意味着我们不能使用SaveAs方法。 好消息是我们可以使用VBA来解决这个限制。

我的方法使用文件系统对象 。 这个非常方便的对象非常适合与文件系统交互。 在使用之前,您需要添加一个参考:

  • 从VBA IDE中单击工具。
  • 点击参考…
  • 从列表中selectWindows脚本宿主对象模型
  • 按OK。

在这里输入图像说明

代码:

 ' Saves the active sheet as a Unicode CSV. Sub SaveAsUnicodeCSV() Dim fso As FileSystemObject ' Provides access to the file system. Dim ts As TextStream ' Writes to your text file. Dim r As Range ' Used to loop over all used rows. Dim c As Range ' Used to loop over all used columns. ' Use the file system object to write to the file system. ' WARNING: This code will overwrite any existing file with the same name. Set fso = New FileSystemObject Set ts = fso.CreateTextFile("!!YOUR FILE PATH HERE.CSV!!", True, True) ' Read each used row. For Each r In ActiveSheet.UsedRange.Rows ' Read each used column. For Each c In r.Cells ' Write content to file. ts.Write c.Value If c.Column < r.Columns.Count Then ts.Write "," Next ' Add a line break, between rows. If r.Row < ActiveSheet.UsedRange.Count Then ts.Write vbCrLf Next ' Close the file. ts.Close ' Release object variables before they leave scope, to reclaim memory and avoid leaks. Set ts = Nothing Set fso = Nothing End Sub 

这段代码遍历活动工作表中每个使用的行。 在每一行中,它循环使用每一列。 每个单元格的内容都附加到您的文本文件中。 在每一行的末尾添加一个换行符。

使用; 只需更换!!您的文件pathHERE.CSV! 与您的文件名称。