VBA:如何删除具有重复值的行?

这是我的代码,我试图删除两行,将有"-----------"如果两行有没有空格,彼此相邻,它需要删除,但如果"-----------"有任何价值低于或高于那么它不应该被删除。

由于某些原因,它给我一个Run-time error 1004无法获得匹配属性。 任何援助将不胜感激。 在这里输入图像说明

 Sub Test() Dim WS As Worksheet, row1 As Long, row2 As Long, rng As Long, n As Long, nlast As Long, rw As Range For Each WS In Sheets nlast = WS.UsedRange.Rows(WS.UsedRange.Rows.count).Row On Error GoTo NextWS With WS If WS.Visible = xlSheetVisible Then row1 = WorksheetFunction.Match("-----------", .Columns("D:L"), 0) row2 = WorksheetFunction.Match("-----------", .Columns("D:L"), 0) If .Range("D" & row1).Value = .Range("D" & row2).Value And _ .Range("E" & row1).Value = .Range("E" & row2).Value And _ .Range("F" & row1).Value = .Range("F" & row2).Value And _ .Range("G" & row1).Value = .Range("G" & row2).Value And _ .Range("H" & row1).Value = .Range("H" & row2).Value And _ .Range("I" & row1).Value = .Range("I" & row2).Value And _ .Range("J" & row1).Value = .Range("J" & row2).Value And _ .Range("K" & row1).Value = .Range("K" & row2).Value Then WS.Rows(1).EntireRow.Delete WS.Rows(2).EntireRow.Delete **ElseIf Row1 +1 <> "" and Row2 +1<>"" else Row1 -1<>"" and Row2 -1<>"" End if End if** *Suede code* End If End If End With NextWS: Err.Clear Next WS End Sub 

更新

  Sub Test() Dim WS As Worksheet Dim n As Long Dim nlast As Long For Each WS In Sheets nlast = WS.UsedRange.Rows(WS.UsedRange.Rows.count).Row For n = nlast To 9 Step -1 If WS.Cells(n, 4).Value = "-----------" And WS.Cells(n, 5).Value = "-----------" And _ WS.Cells(n, 6).Value = "-----------" And WS.Cells(n, 7).Value = "-----------" And WS.Cells(n, 8).Value = "-----------" And _ WS.Cells(n, 9).Value = "-----------" And WS.Cells(n, 10).Value = "-----------" And WS.Cells(n, 11).Value = "-----------" Then ElseIf WS.Cells(n, 4).Value = "-----------" And WS.Cells(n, 5).Value = "-----------" And _ WS.Cells(n, 6).Value = "-----------" And WS.Cells(n, 7).Value = "-----------" And WS.Cells(n, 8).Value = "-----------" And _ WS.Cells(n, 9).Value = "-----------" And WS.Cells(n, 10).Value = "-----------" And WS.Cells(n, 11).Value = "-----------" Then WS.Rows(n).EntireRow.Delete End If Next n Next X Next WS End Sub 

你可以使用AutoFilter()方法和Range对象的Areas属性

 Option Explicit Sub main() Dim area As Range Dim sh As Worksheet For Each sh In Worksheets With sh.Range("D1", sh.Cells(sh.Rows.Count, "D").End(xlUp)) .AutoFilter Field:=1, Criteria1:="-----------" If Application.WorksheetFunction.Subtotal(103, .Cells) > 1 Then Application.DisplayAlerts = False For Each area In .Resize(.Rows.Count - 1).Offset(1).SpecialCells(xlCellTypeVisible).Areas If area.Count > 1 Then area.EntireRow.Delete Next Application.DisplayAlerts = True End If End With Sh.AutoFilterMode = False Next End Sub