Remove duplicates in certain order

Exceladd1ct

Board Regular
Joined
Feb 10, 2019
Messages
76
Hello,
I want to remove all duplicates but keep the last one.
I found this code and adapted it to my situation. But I got stuck because the code only compares and removes the next value upwards in order to keep the last duplicate and delete the rest. But I have 3, 4, 5 or more duplicates.
Can anyone please help me get this done?
Code:
Sub Dupe_Killer_Keep_Last()
Dim lrow As Long

    For lrow = Cells(Rows.Count, 2).End(xlUp).Row To 2 Step -1
        If Cells(lrow, 2) = Cells(lrow, 2).Offset(-1, 0) Then
           Cells(lrow, 2).Offset(-1, 0).Value = ""
        End If
    
    Next lrow
End Sub
 

Excel Facts

Back into an answer in Excel
Use Data, What-If Analysis, Goal Seek to find the correct input cell value to reach a desired result
Code:
Sub Dupe_Killer_Keep_Last()
Dim lrow As Long
For lrow = Cells(Rows.Count, 2).End(xlUp).Row To 2 Step -1
    If Cells(lrow, 2) = Cells(lrow, 2).Offset(-1, 0) Then
        If rng Is Nothing Then
            Set rng = Cells(lrow, 2).Offset(-1, 0)
        Else
            Set rng = Union(rng, Cells(lrow, 2).Offset(-1, 0))
        End If
    End If
Next lrow
If Not rng Is Nothing Then rng.ClearContents
End Sub
 
Upvote 0
Code:
Sub Dupe_Killer_Keep_Last()
Dim lrow As Long,[COLOR=#ff0000] rng As Range[/COLOR]
For lrow = Cells(Rows.Count, 2).End(xlUp).Row To 2 Step -1
    If Cells(lrow, 2) = Cells(lrow, 2).Offset(-1, 0) Then
        If rng Is Nothing Then
            Set rng = Cells(lrow, 2).Offset(-1, 0)
        Else
            Set rng = Union(rng, Cells(lrow, 2).Offset(-1, 0))
        End If
    End If
Next lrow
If Not rng Is Nothing Then rng.ClearContents
End Sub
 
Upvote 0
Solution

Forum statistics

Threads
1,223,234
Messages
6,170,891
Members
452,366
Latest member
TePunaBloke

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top