Excel - 当col3 = col4时删除重复的行

时间:2015-07-31 17:46:11

标签: excel excel-vba vba

我是Macros的新手。我需要以下逻辑的excel宏代码: col1表示column1, col2表示column2

Sub TestDuplicates()
    in worksheet,
    for(each x = row) {
        for(each y = row+1) {
          if(x.col1 == y.col1 && x.col3 == y.col4 && x.col4 == y.col3) {
            Delete y
          }
        }
    }
End Sub

3 个答案:

答案 0 :(得分:2)

Sub TestDuplicates()
    Dim ws As Excel.Worksheet
    Dim lRow As Long

    lRow = 1
    Do While lRow <= ws.UsedRange.Rows.count

        If ws.Range("A" & lRow).Value = ws.Range("A" & lRow + 1).Value And ws.Range("C" & lRow).Value = ws.Range("D" & lRow + 1).Value And ws.Range("D" & lRow).Value = ws.Range("C" & lRow + 1).Value then
             ws.Rows(lRow).EntireRow.Delete
        End If

        lRow = lRow + 1
        ws.Range("A" & lRow).Activate
    Loop
End Sub

答案 1 :(得分:2)

Sub deleteDuplicateRows()
Dim ws As Worksheet
Dim lastRow As Long, curRow As Long, checkRow As Long

Set ws = Sheets("Sheet1")

lastRow = ws.Range("A" & Rows.Count).End(xlUp).Offset(1).Row - 1

For curRow = 2 To lastRow

    For checkRow = curRow + 1 To lastRow
        If ws.Range("A" & curRow).Value = ws.Range("A" & checkRow).Value And ws.Range("B" & curRow).Value = ws.Range("B" & checkRow).Value And ws.Range("C" & curRow).Value = ws.Range("C" & checkRow).Value Then
           ws.Rows(checkRow).Delete
        End If
    Next checkRow
Next curRow

End Sub

检查当前行与从第2行开始的所有剩余行。

答案 2 :(得分:0)

编辑:我似乎在某种程度上误解了你的伪代码,所以这并不是你所要求的。相反,它将每一行与其后的行直接进行比较,而不是将所有剩余的行进行比较。既然bbishopca已经为你实际要求提供了一个很好的解决方案,我会在未经编辑的情况下保留这个,以防有人发现它有用。

Sub AlmostTestDuplicates()
    Dim ws As Worksheet
    Dim rw As Range

    Set ws = ActiveSheet

    For Each rw In ws.Rows
        If ws.Cells(rw.Row, 1).Value = "" Then
            Exit Sub
        End If

        If Cells(rw.Row, 1) = Cells(rw.Row + 1, 1) _
          And Cells(rw.Row, 3) = Cells(rw.Row + 1, 4) _
          And Cells(rw.Row, 4) = Cells(rw.Row + 1, 3) Then
            ws.Rows(rw.Row + 1).Delete
        End If
    Next rw
End Sub