VBA如何在列X的值与列Y的值不匹配时删除行

时间:2016-05-04 18:06:10

标签: excel vba excel-vba

我试图删除列x的单元格值与列y的单元格值不匹配的每一行。我一直遇到一个对象错误,我很确定我错过了一些明显的东西。

Sub Gooddata()

Application.ScreenUpdating = False

lr = Range("C65536").End(xlUp).Row
For a = lr To 1 Step -1
If Cells(a, 8).Value <> Cells(a, 9).Value Then
Cells(a, 3).Select
ActiveCell.EntireRow.Delete = True
End If
Next a

Application.ScreenUpdating = True
End Sub

编辑:我根据评论的建议对代码进行了编辑,输入图像是代码和输出图像。

enter image description here

Sub Gooddata()

Application.ScreenUpdating = False

lr = Range("C65536").End(xlUp).Row
For a = lr To 1 Step -1
If Cells(a, 8).Value <> Cells(a, 9).Value Then
Cells(a, 3).EntireRow.Delete
End If
Next a

Application.ScreenUpdating = True
End Sub

如果以我想要它的方式执行的代码将不会被删除,但是由于逗号和破折号,它下面的行将被删除。

enter image description here

1 个答案:

答案 0 :(得分:1)

试试这个。如果第二列的单词多于第一列XD

,则可能会中断
Sub Gooddata()

Dim lr As Long
Dim arr As Variant
Dim brr As Variant

Application.ScreenUpdating = False

With ActiveSheet

lr = .Cells(.Rows.count, "G").End(xlUp).Row

For A = lr To 1 Step -1

    I = 0
    arr = Split(Trim(.Cells(A, 7).Value2), " ")
    brr = Split(Trim(.Cells(A, 8).Value2), " ")

    For Each e In arr

        '.Cells(A, 9) = e
        If e <> brr(I) Then
            .Cells(A, 3).EntireRow.Delete
            Exit For
            'GoTo yarr
        End If
        I = I + 1

    Next e

'yarr:
'Erase arr
'Erase brr

Next A

End With

Application.ScreenUpdating = True

End Sub

在:

enter image description here

后:

enter image description here