首页 > 解决方案 > 逐行遍历 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文件中的行吗?

标签: excelvba

解决方案


如果我要这样做,我会使用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

结束子


推荐阅读