VBA整理CSV中的相同行

时间:2014-09-09 23:49:45

标签: vba excel-vba csv excel-formula excel

我有一个csv文件,其中一些行是可重复的。任务是在下一个单元格中整理/(替换所有并且只留下一个实例)和多个重复。如何使用VBA执行此操作?

f.e。像这样的东西:

word, description
google, website
apple, fruit
google, website

必须像这样转换为smth:

word, description
google, website, 2
apple, fruit

1 个答案:

答案 0 :(得分:0)

这应该可以解决问题。

Sub doCollate(iStartRow As Integer, iEndRow As Integer, iStartCol As Integer, iEndCol As Integer)

' Loop through the rows with values in them
For iSourceRow = iStartRow To iEndRow - 1

    ' Loop through the remaining rows to check
    For iCheckRow = iSourceRow + 1 To iEndRow

        ' Set a default variable
        bMatch = True

        ' Loop through the columns to check
        For iCol = iStartCol To iEndCol

            ' If these don't match or are blank, indicate that
            If Cells(iSourceRow, iCol) <> Cells(iCheckRow, iCol) _
                Or Cells(iSourceRow, iCol) = "" _
                Or Cells(iCheckRow, iCol) = "" Then
                bMatch = False
                Exit For    ' Exit the "For iCol = iStartCol to iEndCol" loop
            End If

        Next

        ' If there source row matches the destination row...
        If bMatch Then

            ' Increment the "counter"
            If Cells(iSourceRow, iEndCol + 1) = "" Then
                Cells(iSourceRow, iEndCol + 1) = "2"
            Else
                Cells(iSourceRow, iEndCol + 1) = Cells(iSourceRow, iEndCol + 1) + 1
            End If

            ' Clear the "check" row
            Range(Cells(iCheckRow, iStartRow), Cells(iCheckRow, iEndRow)).Clear

        End If

    Next

Next

End Sub

这可以进行优化,因为它会重新检查它产生的空白行,并且在它们上面有空白单元格的行上会失败,但是对于您给出的示例,它可以完美地运行。

请注意,列参数是整数,而不是字母。因此,列A = 1,B = 2,C = 3等