excel - 逐行遍历 CSV 文件以匹配行
问题描述
读取该行后,我想从 CSV 中删除记录。请指导我如何实现这一目标。
我找到了这段代码:
Sub ImportCSVFile(ByVal filePath As String, ByVal ImportToRow As Integer, ByVal StartColumn As Integer)
Dim line As String
Dim arrayOfElements
Dim element As Variant
Open filePath For Input As #1 ' Open file for input
Do While Not EOF(1) ' Loop until end of file
Line Input #1, line
Debug.Print line
arrayOfElements = Split(line, ";") 'Split the line into the array.
Loop
Close #1 ' Close file.
End Sub
它正在读取 CSV 文件并按要求工作。有人可以告诉我如何在阅读后删除CSV文件中的行吗?
解决方案
如果我要这样做,我会使用FileSystemObject来读取一行而不是直接打开文件。我不确定你想做什么来编辑日志文件本身,但我想循环遍历每一行,然后遍历每个标记,我将使用的代码是:
Sub ImportCSVFile(ByVal filePath As String, Optional ByVal ImportToRow As Long = 0, Optional ByVal StartColumn As Long = 1)
'Declare variables.
Dim FSO As Object, sourceFile As Object
Dim line As String, delimiter As String, ForReading As Integer: ForReading = 1
Dim i As Long: i = 1
Dim arrayOfElements As Variant, element As Variant
'Create file system object and open filePath .csv parameter.
Set FSO = CreateObject("Scripting.FileSystemObject")
Set sourceFile = FSO.OpenTextFile(filePath)
delimiter = ";"
'Main loop, reads each line of the .csv file.
Do While Not sourceFile.AtEndOfStream
'Checks if the line being read is at or after the StartColumn parameter.
If i >= StartColumn Then
'Splits line string into an array based on the delimiter.
line = sourceFile.ReadLine
arrayOfElements = Split(line, delimiter)
'Loops through array elements.
For Each element In arrayOfElements
'Your code here.
Next element
End If
'If a value for ImportToRow is provided checks if that line has been reached.
If Not ImportToRow = 0 Then
If i >= ImportToRow Then
Exit Do
End If
End If
i = i + 1: Loop
'Cleans up objects.
Set sourceFile = Nothing: Set FSO = Nothing
结束子
推荐阅读
- python - 如何使用 matplotlib 中设置的自定义数字自定义条形中的颜色?
- ios - 替换所有用户 UIGestures
- python - Pytest - 如何在自定义持续时间内暂停一个测试用例并保持其余测试用例运行?
- highcharts - angular-gridster2:调整大小而不是调整内部孩子的大小
- c++ - 是否可以使用在另一个 lua 文件中定义的表,该表在当前文件中不需要作为模块?
- jenkins - 获取变量中詹金斯每个阶段的结果
- arrays - 使用 VBA 将 Excel 数据导出到 Json 动态数组
- android - Android 游戏 - 如果游戏在 GLSurfaceView 的视频线程中运行,如何正确处理 onPause 和 onResume
- php - Laravel:单击html按钮时显示具有相同URL的列表
- mongodb - 如何使用 id 显示名称但使用 2 个集合 MongoDb 中的数据?