Sub RemoveDuplicatesAndKeepLatest() Dim ws As Worksheet Set ws = [thisworkbook](/activeworkbook-thisworkbook/).Sheets("YourSheetName") ' Assign [Worksheet](/vba/sheets-worksheets) object to "ws". Replace "YourSheetName" with the actual sheet name ' Assuming Column D contains the timestamp Dim lastRow As Long lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row ' Find the last row in the worksheet ' Perform sort operation based on columns 1,3 and timestamp in Column D (adjust accordingly) With ws.Sort .SortFields.Clear .SortFields.Add Key:=ws.Range("A2:A" & lastRow), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal ' Sort on column A ascendingly .SortFields.Add Key:=ws.Range("C2:C" & lastRow), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal ' Sort on column C ascendingly .SortFields.Add Key:=ws.Range("D2:D" & lastRow), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal ' Sort on column D descendingly (to keep the latest) .SetRange ws.Range("A1:AD" & lastRow) .Header = xlYes .MatchCase = False .Orientation = xlTopToBottom .SortMethod = xlPinYin .Apply ' Apply the sorting to the range End With ' Loop through the sorted range and remove duplicates, keeping the latest occurrence Dim currentRow As Long For currentRow = lastRow To 3 Step -1 ' Loop from the bottom of sheet to the top If ws.Cells(currentRow, 1).Value = ws.Cells(currentRow - 1, 1).Value And _ ws.Cells(currentRow, 3).Value = ws.Cells(currentRow - 1, 3).Value Then ' If corresponding cells in Column A and Column C are identical, delete the current row ws.Rows(currentRow).Delete ' Delete the row End If Next currentRow End Sub
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter