如何删除与其他工作表中的条件匹配的行?

时间:2017-04-12 17:54:23

标签: excel-vba vba excel

我有两个电子表格,其中包含我需要清理的数据(名为" fedex"),删除了与另一个电子表格中的数字列表匹配的一些行(名为" sheet1" )。 电子表格" fedex"专栏" H"具有与电子表格匹配的数字" sheet1"栏" A"。

我收到set lastrow = fedex.cells(Rows.count,8)end(xlUp).Row

时收到类型不匹配错误消息

我不确定其他代码是否能正常工作,因为我已经卡在那里了。

这是我的代码:

Sub deletepaidshipments()

Dim fedex As Worksheet
Set fedex = ThisWorkbook.Sheets("fedex_shipment_detail_payer_det")
Dim sheet1 As Worksheet
Set sheet1 = ThisWorkbook.Sheets("sheet1")
Set lastrow = fedex.Cells(Rows.Count, 8).End(xlUp).Row

For x = 2 To lastrow
    t = 0
    On Error Resume Next
    t = Application.WorksheetFunction.Match(fedex.Range("h" & x), sheet1.Range("a :a"), 0)
    On Error GoTo 0
    If t > 0 Then
        fedex.Rows(x, lastrow).Delete        
    End If
Next x

End Sub

1 个答案:

答案 0 :(得分:1)

尝试下面的较短代码版本(代码注释中的解释):

Option Explicit

Sub deletepaidshipments()

Dim FedexSht As Worksheet
Dim Sht1 As Worksheet
Dim LastRow As Long
Dim x As Long

Set FedexSht = ThisWorkbook.Sheets("fedex_shipment_detail_payer_det")
Set Sht1 = ThisWorkbook.Sheets("sheet1")

With FedexSht
    LastRow = .Cells(.Rows.Count, "H").End(xlUp).Row

    For x = LastRow To 2 Step -1 ' allways loop backwards when deleting rows
        If Not IsError(Application.Match(.Range("H" & x).Value, Sht1.Range("A:A"), 0)) Then ' check if there is a match >> delete row
            .Rows(x).Delete
        End If
    Next x
End With

End Sub