Partager via


How to: Delete Duplicate Entries in a Range

The following example shows how to take a range of data in column A and delete duplicate entries. This example uses the AdvancedFilter method of the Range object with the Unique parameter equal to True to get the unique list of data. The Action parameter equals xlFilterInPlace, specifying that the data is filtered in place. If you want to retain your original data, set the Action parameter equal to xlFilterCopy and specify the location where you want the filtered data copied in the CopyToRange parameter. Once the unique values are filtered, this example uses the SpecialCells method of the Range object to find any remaining blank rows and deletes them.

Sample code provided by: MVP Contributor Tom Urtis, Atlas Programming Management | About the Contributor

Sub DeleteDuplicates()
    With Application
        ' Turn off screen updating to increase performance
        .ScreenUpdating = False
        Dim LastColumn As Integer
        LastColumn = Cells.Find(What:="*", After:=Range("A1"), SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column + 1
        With Range("A1:A" & Cells(Rows.Count, 1).End(xlUp).Row)
            ' Use AdvanceFilter to filter unique values
            .AdvancedFilter Action:=xlFilterInPlace, Unique:=True
            .SpecialCells(xlCellTypeVisible).Offset(0, LastColumn - 1).Value = 1
            On Error Resume Next
            ActiveSheet.ShowAllData
            'Delete the blank rows
            Columns(LastColumn).SpecialCells(xlCellTypeBlanks).EntireRow.Delete
            Err.Clear
        End With
        Columns(LastColumn).Clear
        .ScreenUpdating = True
    End With
End Sub

About the Contributor

MVP Tom Urtis is the founder of Atlas Programming Management , a full-service Microsoft Office and Excel business solutions company in Silicon Valley. Tom has over 25 years of experience in business management and developing Microsoft Office applications, and is the co-author of “Holy Macro! It’s 2,500 Excel VBA Examples."