首页 > 解决方案 > 在 VBA 中删除整个 csv 中的 CrLf - ADODB.Stream(Excel 宏)

问题描述

我有一个 vba 宏,它将 BOM 添加到 UTF-8 csv - 它是在 Excel 中成功打开所必需的。但问题是,当行尾有 CrLf 标记时 - excel 在该行下方创建新行。我需要的是删除所有 CrLf 标记(不应该添加 Cr 或 Lf)。它应该会有所帮助,因为 csv 中只会存在 Cr。CrLf 只存在于断层线上。

你能帮助我的源代码吗?我应该添加什么公式来替换源 csv 以在没有任何 CrLf 的情况下使用 BOM 保存目标 csv?

Dim fsT, tFileToOpen, tFileToSave As String

tFileToOpen = "C:\source_NO_BOM.csv"
tFileToSave = "C:\target_WITH_BOM.csv"

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

标签: excelvbautf-8adodbbyte-order-mark

解决方案


您可以创建另一个流对象,更改您插入其中的内容,然后将其导出。

Dim fsT, tFileToOpen, tFileToSave As String
Dim s As String, Newfst As Object


tFileToOpen = "C:\source_NO_BOM.csv"
tFileToSave = "C:\target_WITH_BOM.csv"


tFileToOpenPath = tFileToOpen
tFileToSavePath = tFileToSave


Set fsT = CreateObject("ADODB.Stream"): 'Create Stream object

With fsT
    .Type = 2: 'Specify stream type ? we want To save text/string data.
    .Charset = "utf-8": 'Specify charset For the source text data.
    
    .Open: 'Open the stream
    .LoadFromFile tFileToOpenPath: 'And write the file to the object stream
    s = .ReadText
    s = Replace(s, vbCrLf, "")
End With

Set Newfst = CreateObject("ADODB.Stream")
With Newfst
    .Type = 2
    .Charset = "utf-8"
    .Open
    .WriteText s
    .SaveToFile tFileToSave, 2
End With

推荐阅读