问题描述
我有一个将 BOM 添加到 UTF-8 csv 的 vba 宏 - 这是在 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
解决方法
您可以创建另一个流对象,更改您插入其中的内容,然后将其导出。
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