excel - 在 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
解决方案
您可以创建另一个流对象,更改您插入其中的内容,然后将其导出。
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
推荐阅读
- java - Kotlin 中的压缩字节 []。Java 代码到 Kotlin
- r - 有没有办法将开始和结束时间列组合到 R 中的单个日期时间列(带有分组数据)
- javascript - 如何在 NodeJS 中获得按计划运行的“获取”请求?
- javascript - 满足条件时如何打破 $.each() 循环
- snakemake - temp() 不能在 PBS Torque 集群上使用 snakemake
- java - Android 应用不会写入 Firebase 实时数据库
- mysql - 如何将 memsql 用于组合多个表的报告
- hibernate - 使用 H2/Hibernate/C3P0 模拟瓶颈
- javascript - 如何在给定数据范围的情况下绘制半圆形轮廓 SVG 并用 Javascript 填充?
- xml - PowerShell - XML - 将多个元素附加到远程桌面连接管理器文件中的节点