VBA for Excel:错误424对象必需

时间:2015-10-26 20:45:19

标签: excel vba excel-vba

我正在完成一个脚本,用于验证Sheet1的A列中的单元格(“INCIDENTS”)是否在Sheet2的列A(“INCDB”)中重复,如果单元格是重复的,则删除Sheet1中的整行。

问题是在第一次循环(并删除行)后,它给出了424错误并突出显示If iSrc.Cells.Value = iDst.Cells.Value Then

关于事业的任何想法?这是代码:

Sub CTDeleteDuplicatePaste()

Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim iSrc As Variant
Dim iDst As Variant
Dim rng As Range

Set ws1 = Sheets("INCIDENTS")
Set ws2 = Sheets("INCDB")

For Each iSrc In ws1.Range("A5:A9999" & LastRow)
    For Each iDst In ws2.Range("A5:A9999")
        If iSrc.Cells.Value = iDst.Cells.Value Then
        If rng Is Nothing Then
            Set rng = iSrc.EntireRow
        Else
            Set rng = Union(rng, iSrc.EntireRow)
        End If
            rng.EntireRow.Delete

        End If

    Next iDst
Next iSrc

End Sub

1 个答案:

答案 0 :(得分:1)

我会在没有对象iSrciDst的情况下执行此操作。从相反的顺序 - 这段代码对我有用:

Sub CTDeleteDuplicatePaste()

Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim i As Long
Dim j As Long

Set ws1 = Sheets("INCIDENTS")
Set ws2 = Sheets("INCDB")

For i = 9 To 5 Step -1        'change 9 to 9999 for your real data
    For j = 9 To 5 Step -1    'change 9 to 9999 for your real data
        If Len(ws1.Cells(i, 1).Value) > 0 Then
            If ws1.Cells(i, 1).Value = ws2.Cells(j, 1).Value Then
                ws1.Cells(i, 1).EntireRow.Delete
                GoTo nextIteration
            End If
        End If
    Next
nextIteration:
Next

End Sub

关于.EntireRow.Delete的性能问题,这是附加说明:
Tests on processing 1 million rows
Solution employing Sorting