Brayheart
Brayheart

Reputation: 167

VBA How to Delete Rows when value of Column X does not match value of column Y

I'm trying to delete every row where the cell value for column x does not match the cell value of column y. I keep getting an object error and I'm pretty sure I'm missing something obvious.

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

Edit: I have made edits to the code based on the suggestions of the comments here's the input image the code and the output image.

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

If the code executed in the way that I want it to Old Argus Building 12 will not be deleted however the row below it will because of the comma and dash.

enter image description here

Upvotes: 2

Views: 1018

Answers (1)

findwindow
findwindow

Reputation: 3153

Try this. This could break if second column has more words than first 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

Before:

enter image description here

After:

enter image description here

Upvotes: 1

Related Questions