utf-8 - 将工作表导出为 UTF-8 CSV 文件(使用 Excel-VBA)

标签 utf-8 excel export-to-csv vba

我想导出使用 VBA 以 UTF-8 CSV 创建的文件。通过搜索留言板,我发现了以下将文件转换为 UTF-8 的代码( from this thread ):

Sub SaveAsUTF8() 

    Dim fsT, tFileToOpen, tFileToSave As String 

    tFileToOpen = InputBox("Enter the name and location of the file to convert" & vbCrLf & "With full path and filename ie. C:\MyFolder\ConvertMe.Txt") 
    tFileToSave = InputBox("Enter the name and location of the file to save" & vbCrLf & "With full path and filename ie. C:\MyFolder\SavedAsUTF8.Txt") 

    tFileToOpenPath = tFileToOpen 
    tFileToSavePath = tFileToSave 

Set fsT = CreateObject("ADODB.Stream"): 'Create Stream object
fsT.Type = 2: 'Specify stream type – we want To save text/string data.
fsT.Charset = "utf-8": 'Specify charset For the source text data.

fsT.Open: 'Open the stream
fsT.LoadFromFile tFileToOpenPath: 'And write the file to the object stream

fsT.SaveToFile tFileToSavePath, 2: 'Save the data to the named path

End Sub 

但是,此代码仅将非 UTF-8 文件转换为 UTF-8。如果我以非 UTF-8 格式保存文件,然后将其转换为 UTF-8,它就会丢失其中包含的所有特殊字符,从而使该过程毫无意义!

我想要做的是将打开的文件保存为 UTF-8 (CSV)。有没有办法用 VBA 做到这一点?

n.b.我也在 'ozgrid' forum 上问过这个问题。如果我找到解决方案,将关闭两个线程。

最佳答案

最后,在 Office 2016 中,您可以简单地以 UTF8 格式保存为 CSV。

Sub SaveWorkSheetAsCSV()

Dim wbNew As Excel.Workbook
Dim wsSource As Excel.Worksheet, wsTemp As Excel.Worksheet
Dim name As String



    Set wsSource = ThisWorkbook.Worksheets(1)
    name = "test"
    Application.DisplayAlerts = False 'will overwrite existing files without asking
    Set wsTemp = ThisWorkbook.Worksheets(1)
    Set wbNew = ActiveWorkbook
    Set wsTemp = wbNew.Worksheets(1)
    wbNew.SaveAs name & ".csv", xlCSVUTF8 'new way
    wbNew.Close
    Application.DisplayAlerts = True

End Sub

这会将工作表 1 保存到名为 test 的 csv 中。

关于utf-8 - 将工作表导出为 UTF-8 CSV 文件(使用 Excel-VBA),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12688311/

相关文章:

ruby-on-rails-3 - Rails 将搜索结果持久化到 CSV 输出

JSON 到 CSV 将数据写入 csv 文件

java - IntelliJ IDEA嵌入式终端输出编码问题

excel - 如何使用 VS 2008 VB 将一个单元格或一系列单元格从一个 Excel 电子表格复制到另一个 Excel 电子表格

Java - 从剪贴板检索 XML (Excel) 电子表格

excel - 在 Excel 2019 上运行 Selenium VBA 时出现自动化错误

r - 将数值向量作为字符导出到 CSV

python - 使用 json.dumps 将 UTF-8 文本保存为 UTF-8,而不是\u 转义序列

utf-8 - 内容处理特殊字符

换行后 Unicode 字符变得困惑