Skip to main content

Excel Macro: Delete Duplicate Entries in a Range

The following example shows how to take a range of data in column A and delete duplicate entries.

Delete Duplicate Entries in a Range

Sub DeleteDuplicates()

    Dim LastColumn As Integer
    Dim LastRow As Integer
    LastColumn = ActiveSheet.UsedRange.Columns.Count + 1
    LastRow = Cells(Rows.Count, 1).End(xlUp).Row
    ' Turn off screen updating to increase performance
    Application.ScreenUpdating = False
    With Range("A1:A" & LastRow)
        ' Use AdvanceFilter to filter unique values
        .AdvancedFilter Action:=xlFilterInPlace, Unique:=True
        ' Use a helper column to mark unique columns
        .SpecialCells(xlCellTypeVisible).Offset(0, LastColumn - 1).Value = 1
        On Error Resume Next
        ' Delete the blank rows
    End With
    ' clear the helper column
    Application.ScreenUpdating = True

End Sub

How This Macro Works

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.

Remove Duplicates in Excel 2013 or later

If you use Excel 2013 or later, you can use RemoveDuplicates method of Range object to remove duplicates:

ActiveSheet.Range("A:A").RemoveDuplicates Columns:=1, Header:=xlYes

Most VBA code should be placed in Standard Modules unless specified.

If you see a comment '------------------ Modules------------------ in the code header that means put the code in a Standard Module. For more information, learn this course: Where should I put the Excel VBA code?

The following steps teach you how to put VBA code into a Standard Module:

  1. Activate the Visual Basic Editor by pressing ALT + F11.
  2. Right-click the project/workbook name in the Project Window.
  3. Choose Insert -> Module.
  4. Type or paste the code in the newly created module. You will probably need to change the sheet name, the range address, and the save location.
  5. Click Run button on the Visual Basic Editor toolbar.
  6. For more information, learn this course: Programming with Excel VBA

Leave a comment

Your email address will not be published. Required fields are marked *

Format your code: <pre><code class="language-vba">place your code here</code></pre>