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

我是macros的新手。 我需要以下逻辑的excelmacros代码: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 

 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行开始检查当前行与所有剩余的行。

 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 

编辑:我似乎误解了你的伪代码有点,所以这不完全相同你问。 相反,它会将每行直接与行之后的行进行比较,而不是对所有剩余的行进行比较。 由于bbishopca已经为你真正要求的东西提供了一个很好的解决scheme,所以我会把它留在这里,以防有人发现它有用。

 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