微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 VBA 中删除整个 csv 中的 CrLf - ADODB.StreamExcel 宏

如何解决在 VBA 中删除整个 csv 中的 CrLf - ADODB.StreamExcel 宏

我有一个将 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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。