如果在Excel中重复的话,如何比较四个不同的列并删除其中一行?

时间:2019-03-06 05:16:52

标签: excel

好的,我知道这听起来像是其他一些Excel问题,但是我看不到与此类似的问题。

基本上,我的csv充满了一些snort警报。我正在尝试过滤此csv文件,使其仅包括唯一的连接,而不包括整个握手。

采用非常简化的.csv:

    IP1      Port1    IP2      Port2
1   192.1    55       68.1     80    
2   195.4    21       67.1     70
3   68.1     80       192.1    55
4   195.4    67       67.1     70

我想比较这些行,如果它们像第1行和第3行一样重复,我想删除其中之一。 (哪一个并不重要)很多条目都需要手工来完成。我想知道是否有办法在Excel中完成此操作?

2 个答案:

答案 0 :(得分:0)

我不清楚为什么这对67.1 / 70不被视为重复。

Option Explicit

Sub delDupes()

    Dim arr As Variant

    With Worksheets("sheet2")

        'collect columns C & D, clear data
        With .Range(.Cells(1, "C"), .Cells(.Rows.Count, "D").End(xlUp))
            arr = .Value
            .Offset(1, 0).Clear
        End With

        'put values from C & D into A & B
        With .Cells(.Rows.Count, "A").End(xlUp)
            .Offset(1, 0).Resize(UBound(arr, 1), UBound(arr, 2)) = arr
        End With

        'remove duplicates
        .Range("A:B").RemoveDuplicates Columns:=Array(1, 2), Header:=xlYes

        'collect processed values
        arr = Application.Match(.Cells(1, "C").Value, .Range("A:A"), 0)
        With .Range(.Cells(arr, "A"), .Cells(.Rows.Count, "B").End(xlUp))
            .Parent.Cells(1, "C").Resize(.Rows.Count, .Columns.Count) = .Value
            .Clear
        End With

    End With

End Sub

答案 1 :(得分:0)

您可以尝试:

Option Explicit

Sub test()

    Dim ws1 As Worksheet, ws2 As Worksheet, Lastrow1 As Long, Lastrow2 As Long, i As Long, Times1 As Long, Times2 As Long
    Dim rng1 As Range, rng2 As Range
    Dim IP As String, Port As String

    'Declare workbook
    With ThisWorkbook
        'Set ws & ws2
        Set ws1 = .Worksheets("Sheet1")
        Set ws2 = .Worksheets("Sheet2")
        'Find last row of sheet 1 column a
        Lastrow1 = ws1.Cells(ws1.Rows.Count, "A").End(xlUp).Row
        'Find last row of sheet 2 column a
        Lastrow2 = ws2.Cells(ws2.Rows.Count, "A").End(xlUp).Row
        'Set  range 1 (sheet 2 column A from row 2 to last row)
        Set rng1 = ws2.Range("A2:A" & Lastrow2)
        'Set  range 2 (sheet 2 column b from row 2 to last row)
        Set rng2 = ws2.Range("B2:B" & Lastrow2)
        'Loop sheet 1
        For i = Lastrow1 To 2 Step -1
            'Assighn value to Ip ( sheet 1 column a row i)
            IP = ws1.Range("A" & i).Value
            'Assighn value to Ip ( sheet 1 column b row i)
            Port = ws1.Range("B" & i).Value
            'Check how many times Ip appears in sheet 2 column a
            Times1 = Application.WorksheetFunction.CountIf(rng1, IP)
            'Check how many times port appears in sheet 2 column b
            Times2 = Application.WorksheetFunction.CountIf(rng2, Port)
            'If both Ip & port appears more than 0 times
            If Times1 > 0 And Times2 > 0 Then
                'Delete the row from sheet1
                ws1.Rows(i).EntireRow.Delete
            End If

        Next i

    End With

End Sub