Removing duplicates in excel vba

In this Article

  • RemoveDuplicates Method
  • RemoveDuplicates Usage Notes
    • Sample Data for VBA Examples
    • Remove Duplicate Rows
    • Remove Duplicates Comparing Multiple Columns
    • Removing Duplicate Rows from a Table
    • Remove Duplicates From Arrays
    • Removing Duplicates from Rows of Data Using VBA

This tutorial will demonstrate how to remove duplicates using the RemoveDuplicates method in VBA.

RemoveDuplicates Method

When data is imported or pasted into an Excel worksheet, it can often contain duplicate values.  You may need to clean the incoming data and remove duplicates.

Fortunately, there is an easy method within the Range object of VBA which allows you to do this.

Range(“A1:C8”).RemoveDuplicates Columns:=1, Header:=xlYes

Syntax is:

RemoveDuplicates([Columns],[Header]

  • [Columns] – Specify which columns are checked for duplicate values. All columns much match to be considered a duplicate.
  • [Header] – Does data have a header? xlNo (default), xlYes, xlYesNoGuess

Technically, both parameters are optional. However, if you don’t specify the Columns argument, no duplicates will be removed.

The default value for Header is xlNo. Of course it’s better to specify this argument, but if you have a header row, it’s unlikely the header row will match as a duplicate.

RemoveDuplicates Usage Notes

  • Before using the RemoveDuplicates method, you must specify a range to be used.
  • The RemoveDuplicates method will remove any rows with duplicates found, but will keep the original row with all values.
  • The RemoveDuplicates method only works on columns and not on rows, but VBA code can be written to rectify this situation (see later).

Sample Data for VBA Examples

In order to show how the example code works, the following sample data is used:

VBA 16 PIC 01

Remove Duplicate Rows

This code will remove all duplicate rows based only on values in column A:

Sub RemoveDupsEx1()
Range(“A1:C8”).RemoveDuplicates Columns:=1, Header:=xlYes
End Sub

Notice that we explicitly defined the Range “A1:C8”. Instead you can used the UsedRange. The UsedRange will determine the last used row and column of your data and apply RemoveDuplicates to that entire range:

Sub RemoveDups_UsedRange()
ActiveSheet.UsedRange.RemoveDuplicates Columns:=1, Header:=xlYes
End Sub

UsedRange is incredibly useful, removing the need for you to explicitly define the range.

After running these code, your worksheet will now look like this:

VBA 16 PIC 02

Notice that because only column A (column 1) was specified, the ‘Apples’ duplicate formerly in row 5 has been removed. However, the Quantity (column 2) is different.

To remove duplicates, comparing multiple columns, we can specify those columns using an Array method.

Remove Duplicates Comparing Multiple Columns

Sub RemoveDups_MultColumns()
ActiveSheet.UsedRange.RemoveDuplicates Columns:=Array(1, 2) , Header:=xlYes
End Sub

The Array tells VBA to compare the data using both columns 1 and 2 (A and B).

The columns in the array do not have to be in consecutive order.

Sub SimpleExample()
ActiveSheet.UsedRange.RemoveDuplicates Columns:=Array(3, 1) , Header:=xlYes
End Sub

In this example, columns 1 and 3 are used for the duplicate comparison.

This code example uses all three columns to check for duplicates:

Sub SimpleExample()
ActiveSheet.UsedRange.RemoveDuplicates Columns:=Array(1, 2, 3) , Header:=xlYes
End Sub

Removing Duplicate Rows from a Table

The RemoveDuplicates can also be applied to an Excel table in exactly the same way. However, the syntax is slightly different.

Sub SimpleExample()
ActiveSheet.ListObjects("Table1").DataBodyRange.RemoveDuplicates Columns:=Array(1, 3), _
Header:=xlYes
End Sub

This will remove the duplicates in the table based on columns 1 and 3 (A and C).  However, it does not tidy up the color formatting of the table, and you will see colored blank rows left behind at the bottom of the table.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

automacro

Learn More

Remove Duplicates From Arrays

If you need to remove duplicate values from an array, of course you can output your array into Excel, use the RemoveDuplicates method, and re-import the array.

However, we also wrote a VBA procedure to remove duplicates from an array.

Removing Duplicates from Rows of Data Using VBA

The RemoveDuplicates method only works on columns of data, but with some ‘out of the box’ thinking, you can create a VBA procedure to deal with rows of data.

Suppose that your data looks like this on your worksheet:

VBA 16 PIC 03

You have the same duplicates as before in columns B and E, but you cannot remove them using the RemoveDuplicates method.

The answer is to use VBA to create an additional worksheet, copy the data into it transposing it into columns, remove the duplicates, and then copy it back transposing it back into rows.

Sub DuplicatesInRows()
    'Turn off screen updating and alerts – we want the code to run smoothly without the user seeing
    ‘what is going on
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    'Add a new worksheet
    Sheets.Add After:=ActiveSheet
    'Call the new worksheet 'CopySheet'
    ActiveSheet.Name = "CopySheet"
    'Copy the data from the original worksheet
    Sheets("DataInRows").UsedRange.Copy
    'Activate the new sheet that has been created
    Sheets("CopySheet").Activate
    'Paste transpose the data so that it is now in columns
    ActiveSheet.Range("A1").PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
        False, Transpose:=True
   'Remove the duplicates for columns 1 and 3
    ActiveSheet.UsedRange.RemoveDuplicates Columns:=Array(1, 3), Header _
        :=xlYes
    'Clear the data in the original worksheet
    Sheets("DataInRows").UsedRange.ClearContents
    'Copy the columns of data from the new worksheet created
   Sheets("Copysheet").UsedRange.Copy
   'Activate the original sheet
    Sheets("DataInRows").Activate
    
   'Paste transpose the non-duplicate data
    ActiveSheet.Range("A1").PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
        False, Transpose:=True
    'Delete the copy sheet - no longer needed
    Sheets("Copysheet").Delete
    'Activate the original sheet
    Sheets("DataInRows").Activate
    'Turn back on screen updating and alerts
    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
End Sub

This code assumes that the original data in rows is held on a worksheet called ‘DataInRows’

After running the code, your worksheet will look like this:

VBA 16 PIC 04

The ‘Apples’ duplicate in column E has now been removed. The user is back in a clean position, with no extraneous worksheets hanging around, and the whole process has been done smoothly with no screen flickering or warning messages.

Assume I have a block of data in Excel 2010, 100 rows by 3 columns.

Column C contains some duplicates, say it starts off as

1, 1, 1, 2, 3, 4, 5, ….. , 97, 98

Using VBA, I would like to remove the duplicate rows so I am left with 98 rows and 3 columns.

1, 2, 3, ….. , 97, 98

I know there is a button in Excel 2010 to do that but it inteferes with the rest of my code subsequently and gives incorrect results.

Furthermore, I would like to do it in arrays, then paste the results on the worksheet, rather than methods such as Application.Worksheetfunction.countif(.....

So something like:

Dim myarray() as Variant
myarray=cells(1,1).Currentregion.value

Dim a as Long

For a=1 to Ubound(myarray,1)

    'something here to 

Next a

Community's user avatar

asked Aug 8, 2012 at 17:39

Yht H's user avatar

1

I answered a similar question. Here is the code I used:

Dim dict As Object
Dim rowCount As Long
Dim strVal As String

Set dict = CreateObject("Scripting.Dictionary")

rowCount = Sheet1.Range("A1").CurrentRegion.Rows.Count

'you can change the loop condition to iterate through the array rows instead
Do While rowCount > 1
  strVal = Sheet1.Cells(rowCount, 1).Value2

  If dict.exists(strVal) Then
    Sheet1.Rows(rowCount).EntireRow.Delete
  Else
    'if doing this with an array, then add code in the Else block
    ' to assign values from this row to the array of unique values
    dict.Add strVal, 0
  End If

  rowCount = rowCount - 1
Loop

Set dict = Nothing

If you want to use an array, then loop through the elements with the same conditional (if/else) statements. If the item doesn’t exist in the dictionary, then you can add it to the dictionary and add the row values to another array.

Honestly, I think the most efficient way is to adapt code you’d get from the macro recorder. You can perform the above function in one line:

    Sheet1.UsedRange.RemoveDuplicates Columns:=3, Header:=xlYes

Community's user avatar

answered Aug 8, 2012 at 17:56

Zairja's user avatar

ZairjaZairja

1,43112 silver badges31 bronze badges

5

Function eliminateDuplicate(poArr As Variant) As Variant
    Dim poArrNoDup()

    dupArrIndex = -1
    For i = LBound(poArr) To UBound(poArr)
        dupBool = False

        For j = LBound(poArr) To i
            If poArr(i) = poArr(j) And Not i = j Then
                dupBool = True
            End If
        Next j

        If dupBool = False Then
            dupArrIndex = dupArrIndex + 1
            ReDim Preserve poArrNoDup(dupArrIndex)
            poArrNoDup(dupArrIndex) = poArr(i)
        End If
    Next i

    eliminateDuplicate = poArrNoDup
End Function

Andriy Makukha's user avatar

answered Oct 30, 2013 at 21:12

RBILLC's user avatar

RBILLCRBILLC

1702 silver badges6 bronze badges

2

Simple function to remove duplicates from a 1D array

Private Function DeDupeArray(vArray As Variant) As Variant
  Dim oDict As Object, i As Long
  Set oDict = CreateObject("Scripting.Dictionary")
  For i = LBound(vArray) To UBound(vArray)
    oDict(vArray(i)) = True
  Next
  DeDupeArray = oDict.keys()
End Function

Edit:

With stdVBA (a library largely maintained by myself) you can use:

uniqueValues = stdEnumerator.CreateFromArray(myArray).Unique().AsArray()

answered Jun 14, 2019 at 8:51

Sancarn's user avatar

SancarnSancarn

2,54318 silver badges43 bronze badges

3

An improvement on @RBILLC and @radoslav006 answers, this version searches the array with the duplicates removed for existing values so it searchs less values to find a duplicate.

Public Function RemoveDuplicatesFromArray(sourceArray As Variant)
    Dim duplicateFound As Boolean
    Dim arrayIndex As Integer, i As Integer, j As Integer
    Dim deduplicatedArray() As Variant
    
    arrayIndex = -1
    deduplicatedArray = Array(1)

    For i = LBound(sourceArray) To UBound(sourceArray)
        duplicateFound = False

        For j = LBound(deduplicatedArray) To UBound(deduplicatedArray)
            If sourceArray(i) = deduplicatedArray(j) Then
                duplicateFound = True
                Exit For
            End If
        Next j

        If duplicateFound = False Then
            arrayIndex = arrayIndex + 1
            ReDim Preserve deduplicatedArray(arrayIndex)
            deduplicatedArray(arrayIndex) = sourceArray(i)
        End If
    Next i

    RemoveDuplicatesFromArray = deduplicatedArray
End Function

answered Oct 25, 2020 at 5:34

Darryls99's user avatar

Darryls99Darryls99

9116 silver badges10 bronze badges

Here’s another approach for working with an array:

Sub tester()

    Dim arr, arrout
    
    arr = Range("A1").CurrentRegion.Value   'collect the input array
     
    arrout = UniqueRows(arr)                'get only unique rows
    
    Range("H1").Resize(UBound(arrout, 1), UBound(arrout, 2)).Value = arrout
    
End Sub




Function UniqueRows(arrIn As Variant) As Variant
    Dim keys, rw As Long, col As Long, k, sep, arrout
    Dim dict As Object, lbr As Long, lbc As Long, ubr As Long, ubc As Long, rwOut As Long
    Set dict = CreateObject("scripting.dictionary")
    'input array bounds
    lbr = LBound(arrIn, 1)
    ubr = UBound(arrIn, 1)
    lbc = LBound(arrIn, 2)
    ubc = UBound(arrIn, 2)
    ReDim keys(lbr To ubr)
    'First pass:collect all the row "keys" in an array 
    '    and unique keys in a dictionary
    For rw = lbr To ubr
        k = "": sep = ""
        For col = lbc To ubc
            k = k & sep & arrIn(rw, col)
            sep = Chr(0)
        Next col
        keys(rw) = k     'collect key for this row
        dict(k) = True   'just collecting unique keys
    Next rw

    'Resize output array to # of unique rows
    ReDim arrout(lbr To dict.Count + (lbr - 1), lbc To ubc)
    rwOut = lbr
    'Second pass: copy each unique row to the output array
    For rw = lbr To ubr
        If dict(keys(rw)) Then      'not yet output?
            For col = lbc To ubc    'copying this row over to output...
                arrout(rwOut, col) = arrIn(rw, col)
            Next col
            rwOut = rwOut + 1      'increment output "row"
            dict(keys(rw)) = False 'flag this key as copied
        End If
    Next rw
    UniqueRows = arrout
End Function

answered Jan 6, 2022 at 23:21

Tim Williams's user avatar

Tim WilliamsTim Williams

150k8 gold badges96 silver badges124 bronze badges

Answer from @RBILLC could be easily improved by adding an Exit For inside internal loop:

Function eliminateDuplicate(poArr As Variant) As Variant
    Dim poArrNoDup()

    dupArrIndex = -1
    For i = LBound(poArr) To UBound(poArr)
        dupBool = False

        For j = LBound(poArr) To i
            If poArr(i) = poArr(j) And Not i = j Then
                dupBool = True
                Exit For
            End If
        Next j

        If dupBool = False Then
            dupArrIndex = dupArrIndex + 1
            ReDim Preserve poArrNoDup(dupArrIndex)
            poArrNoDup(dupArrIndex) = poArr(i)
        End If
    Next i

    eliminateDuplicate = poArrNoDup
End Function

answered Feb 21, 2020 at 13:48

radoslav006's user avatar

I think this is really a case for using excel’s native functions, at least for the initial array acquisition, and I don’t think there’s any simpler way to do it. This sub will output the unique values starting in column 5. I assumed that the target range was empty, so if it’s not, change r and c.

Sub testUniques()
    
    Dim arr, r As Long, c As Long, h As Long, w As Long
    Dim this As Worksheet: Set this = ActiveSheet
    arr = Application.Unique(this.Cells(1, 1).CurrentRegion)
    
    r = 1
    c = 5
    h = UBound(arr, 1) - 1
    w = UBound(arr, 2) - 1
    
    this.Range(this.Cells(r, c), this.Cells(r + h, c + w)) = arr
    
End Sub

answered Aug 18, 2021 at 22:03

Chris Strickland's user avatar

Chris StricklandChris Strickland

3,3281 gold badge15 silver badges18 bronze badges

0

I know this is old, but here’s something I used to copy duplicate values to another range so that I could see them quickly to establish data integrity for a database I was standing up from various spreadsheets. To make the procedure delete the duplicates it would be as simple as replacing the dupRng lines with Cell.Delete Shift:=xlToLeft or something to that effect.

I haven’t tested that personally, but it should work.

Sub PartCompare()
    Dim partRng As Range, partArr() As Variant, i As Integer
    Dim Cell As Range, lrow As Integer

    lrow = ThisWorkbook.Worksheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row
    i = 0

    Set partRng = ThisWorkbook.Worksheets("Sheet1").Range(Cells(1, 1), Cells(lrow, 1))

    For Each Cell In partRng.Cells
        ReDim Preserve partArr(i)
        partArr(i) = Cell.Value
        i = i + 1
    Next

    Dim dupRng As Range, j As Integer, x As Integer, c As Integer

    Set dupRng = ThisWorkbook.Worksheets("Sheet1").Range("D1")

    x = 0
    c = 1
    For Each Cell In partRng.Cells
        For j = c To UBound(partArr)
            If partArr(j) = Cell.Value Then
                dupRng.Offset(x, 0).Value = Cell.Value
                dupRng.Offset(x, 1).Value = Cell.Address()
                x = x + 1
                Exit For
            End If
        Next j
        c = c + 1
    Next Cell
End Sub

answered May 16, 2019 at 13:35

TOTM's user avatar

TOTMTOTM

1077 bronze badges

Remove duplicates (plus related row items) from array

As OP wanted a VBA solution close to RemoveDuplicates, I demonstrate an array approach using a ►dictionary to get not the unique items per se (dict.keys), but the related row indices of first occurrencies (dict.items).

These are used to retain the whole row data via procedure LeaveUniques profiting from the advanced possibilities of the ►Application.Index() function — c.f. Some peculiarities of the the Application.Index function

Example Call

Sub ExampleCall()
'[0]define range and assign data to 1-based 2-dim datafield
    With Sheet1                   ' << reference to your project's sheet Code(Name)
        Dim lastRow: lastRow = .Cells(.Rows.Count, "C").End(xlUp).Row
        Dim rng:  Set rng = .Range("C2:E" & lastRow)
    End With
    Dim data: data = rng        ' assign data to 2-dim datafield
'[1]get uniques (column 1) and remove duplicate rows
    LeaveUniques data           ' << call procedure LeaveUniques (c.f. RemoveDuplicates)
'[2]overwrite original range
    rng.Clear
    rng.Resize(UBound(data), UBound(data, 2)) = data
End Sub

Procedure LeaveUniques

Sub LeaveUniques(ByRef data As Variant, Optional ByVal colNum As Long = 1)
'Purpose: procedure removes duplicates of given column number in entire array
    data = Application.Index(data, uniqueRowIndices(data, colNum), nColIndices(UBound(data, 2)))
End Sub

Help functions to LeaveUniques

Function uniqueRowIndices(data, Optional ByVal colNum As Long = 1)
'Purpose: return data index numbers referring to uniques
'a) set late bound dictionary to memory
    Dim dict As Object
    Set dict = CreateObject("Scripting.Dictionary")
'b) slice e.g. first data column (colNum = 1)
    Dim colData
    colData = Application.Index(data, 0, colNum)
'c) fill dictionary with uniques referring to first occurencies
    Dim i As Long
    For i = 1 To UBound(colData)
        If Not dict.exists(dict(colData(i, 1))) Then dict(colData(i, 1)) = i
    Next
'd) return 2-dim array of valid unique 1-based index numbers
    uniqueRowIndices = Application.Transpose(dict.items)
End Function

Function nColIndices(ByVal n As Long)
'Purpose: return "flat" array of n column indices, e.g. for n = 3 ~> Array(1, 2, 3)
    nColIndices = Application.Transpose(Evaluate("row(1:" & n & ")"))
End Function

answered Oct 25, 2020 at 19:52

T.M.'s user avatar

T.M.T.M.

9,2293 gold badges32 silver badges57 bronze badges

RemoveDuplicates in VBA Excel

Duplicate values are often not required in Excel, especially when you want to have unique values count. It is because we usually have a different set of data to work with, and we see a bunch of duplicate values in it.

We hope you are familiar with removing duplicates in excelTo remove duplicates from the excel column, the user can adopt any of the three well-known methods: Using data tools group, Using the advanced filter in excel, Conditional formatting in excel.read more worksheets. If not, there is nothing to worry about. We will show you a simple example for you. In VBA, too, we can perform the remove duplicates method.

So, It has removed all the duplicate values of the “Region” heading. Similarly, we can do this task with the help of the VBA codeVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more.

Table of contents
  • RemoveDuplicates in VBA Excel
    • How to Remove Duplicate Values in VBA Coding?
    • Examples of Remove Duplicate Values in VBA Coding
      • VBA Remove duplicates – Example #1
      • VBA Remove duplicates – Example #2
      • VBA Remove Duplicates from Multiple Columns – Example #3
    • Recommended Articles

VBA Remove Duplicates

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA Remove Duplicates (wallstreetmojo.com)

How to Remove Duplicate Values in VBA Coding?

To remove duplicate values, first, we need to mention the range we are referring to. Then we can access the “Remove Duplicates” method. So syntax will be as follows.

VBA Remove 1

[Column]: Which selection column do we need to remove duplicates? We need to mention the column number of the selected range.

[Header]: The range you have selected has either headers or not. So, we have three options to work with here.

  • xlYes: If the data has headers, then you can select this.
  • xlNo: If the data doesn’t have headers, you can select this.
  • xlGuess: This option will allow Excel to guess the data headers.

So, using these parameters, we can remove duplicates with just a click of a button without breaking our sweat.

In the below section, we will show examples to VBAHere’s a list of the top examples of VBA Macro code in Excel: Print All Sheet Names, Insert Different Color Index in VBA, Insert Worksheets as Much as You want, Insert Blank Row After Every Other Row
Highlight Spelling Mistakes.
read more
removing duplicates. Follow the steps carefully to write the code on your own.

Examples of Remove Duplicate Values in VBA Coding

Below are the examples of RemoveDuplicate in Values VBA.

VBA Remove duplicates – Example #1

Consider the below data for this example as well.

Remove Duplicate Example 1

We need to remove “Region” column duplicates from the above data, so follow the steps below to write the code.

Step 1: Start the sub procedure by giving a Macro code name.

Step 2: Mention the range of data by using the VBA Range object.

Code:

Sub Remove_Duplicates_Example1()

  Range ("A1:C9").

End Sub

VBA Remove Duplicate Step 1

Step 3: After mentioning the range access VBA “RemoveDuplicates” method.

Code:

Sub Remove_Duplicates_Example1()

  Range("A1:C9").RemoveDuplicates

End Sub

VBA Remove Duplicate Step 2

Step 4: First argument in which column we need to remove the duplicate values. In this example, we need to remove the duplicates from the first column.

Code:

Sub Remove_Duplicates_Example1()

  Range("A1:C9").RemoveDuplicates Columns:=1,

End Sub

VBA Remove Duplicate Step 3

Step 5: Next thing is whether the data has headers or not. In this case, we have headers, so select “xlYes.”

Code:

Sub Remove_Duplicates_Example1()

  Range("A1:C9").RemoveDuplicates Columns:=1, Header:=xlYes

End Sub

VBA Remove Duplicate Step 4

Run this code. It will remove duplicates from the selected region.

VBA Remove Duplicate Step 5

It is a straightforward way of referring to the range of cells. However, if you wish to select the range on your own and remove duplicates, then we need to use the variable to work with. In the below example, we will show you how to use variables in VBA.

VBA Remove duplicates – Example #2

In the above example, we have specifically supplied the range of cells. Now, we will see how to work with selecting our cells.

For example, we have a few data sets, as shown in the image below.

VBA Remove Duplicate Example 2

We cannot explicitly specify the range of cells so we will assign the selection as the range.

Step 1: Declare the variable as Range.

Code:

Sub Remove_Duplicates_Example2()

  Dim Rng As Range

End Sub

VBA Remove Duplicate Example 2-1

Step 2: Range is an object. We will set the range as our selection.

Code:

Sub Remove_Duplicates_Example2()

  Dim Rng As Range
  
  Set Rng = Selection

End Sub

Example 2-2

Step 3: Instead of a range of cells, we can use the variable “rng.”

Code:

Sub Remove_Duplicates_Example2()

  Dim Rng As Range

  Set Rng = Selection

  Rng.RemoveDuplicates Columns:=1, Header:=xlYes

End Sub

Example 2-3

Before running the code, we must select the range of cells first. Then, we can remove duplicates from the selected range of cells.

Example 2-4

VBA Remove Duplicates from Multiple Columns – Example #3

We can also use VBA to remove duplicate values from excel columnsTo remove duplicates from the excel column, the user can adopt any of the three well-known methods: Using data tools group, Using the advanced filter in excel, Conditional formatting in excel.read more. Finally, we need to use an array to remove multiple columns and mention the column numbers.

For example, look at the example data image.

Remove Multiple Columns Example 3

We have duplicate values in the first column and fourth column. So, we will remove these columns. Use the below code to VBA to remove duplicates.

Code:

Sub Remove_Duplicates_Example3()

  Dim Rng As Range
  Set Rng = Range("A1:D9")

  Rng.RemoveDuplicates Columns:=Array(1, 4), Header:=xlYes

End Sub

You can download this VBA Remove Duplicates Excel here. VBA Remove Duplicates Excel Template

Recommended Articles

This article has been a guide to VBA Remove Duplicates. Here, we learn how to remove duplicate values in Excel VBA, examples and download an Excel template. Below are some useful Excel articles related to VBA: –

  • VBA LikeVBA Like is a comparison operator that matches a pattern by comparing a given string as an argument in a set of strings.read more
  • VBA Pivot TablePivot Tables are at the heart of summarizing a large amount of data.  We can also use VBA coding to automate the process of creating a pivot table.read more
  • Find Duplicates in ExcelIn MS Excel, the duplicate values can be found and removed from a data set. Depending on your data and requirement, the most commonly used methods are the conditional formatting feature or the COUNTIF formula to find and highlight the duplicates for a specific number of occurrences. The columns of the data set can be then filtered to view the duplicate values.
    read more
  • Highlight Duplicates in ExcelHighlight Cells Rule, which is available under Conditional Formatting under the Home menu tab, can be used to highlight duplicate values in the selected dataset, whether it is a column or row of a table.read more

Удаление повторяющихся значений (дубликатов) в диапазоне ячеек с помощью кода VBA Excel. Метод Range.RemoveDuplicates — синтаксис, параметры, примеры.

Метод Range.RemoveDuplicates

Метод Range.RemoveDuplicates предназначен в VBA Excel для удаления повторяющихся значений по столбцам в заданном диапазоне ячеек рабочего листа. Строки с обнаруженными дубликатами удаляются целиком.

Синтаксис метода Range.RemoveDuplicates

expression. RemoveDuplicates (Columns , Header),

где expression — переменная или выражение, возвращающее объект Range.

Параметры метода Range.RemoveDuplicates

Наименование Описание
Columns Массив индексов столбцов, содержащих ячейки с повторяющимися значениями. Обязательный параметр. Тип данных – Variant.
Header Указывает, содержит ли первая строка диапазона заголовок, который не участвует в поиске дубликатов:

  • xlNo — первая строка списка не содержит заголовок (значение по умолчанию);
  • xlYes — первая строка диапазона содержит заголовок;
  • xlGuess — VBA Excel решает сам, есть ли у списка заголовок.

Необязательный параметр. Тип данных – XlYesNoGuess.

Метод работает как с круглыми скобками, в которые заключены параметры, так и без них. Если требуется указать несколько столбцов в параметре Columns, следует использовать функцию Array, например, Array(2, 3).

Примеры удаления дубликатов

Исходная таблица для всех примеров

Исходная таблица для удаления дубликатов

По третьей колонке легко определить, какие строки были удалены.

Пример 1
Удаление повторяющихся значений по первому столбцу:

Range("A1:C10").RemoveDuplicates 1

или

Range(Cells(1, 1), Cells(10, 3)).RemoveDuplicates (1)

Второй вариант позволяет использовать вместо индексов строк и столбцов переменные. Наличие или отсутствие скобок, в которые заключен параметр Columns, на работу метода не влияет.

Результат:

Пример 2
Удаление дубликатов по первому столбцу с указанием, что первая строка содержит заголовок:

Range("A1:C10").RemoveDuplicates 1, xlYes

Результат:

Здесь мы видим, что первая строка не учитывалась при поиске повторяющихся значений.

Пример 3
Удаление дубликатов по первому и второму столбцам:

Range("A1:C10").RemoveDuplicates Array(1, 2)

Результат:

Обратите внимание, что при удалении повторяющихся значений по нескольким столбцам, будут удалены дубли только тех строк, в которых во всех указанных столбцах содержатся одинаковые значения. В третьем примере удалены «лишние» строки с дублями значений по двум первым столбцам: Корова+Лягушка, Свинья+Бурундук и Овца+Собака.


Смотрите, как отобрать уникальные значения из списка в VBA Excel с помощью объекта Collection и объекта Dictionary.

VBA Remove Duplicates

VBA Remove Duplicates

Excel has a feature which is used for removing the duplicate values from the selected cells, rows or table. What if this process we automate in VBA? Yes, the process of removing the duplicate can be automated in VBA in a form of Macro. In the process of removing the duplicate, once it is completed the unique values remain in the list or table. This can be in with the help of Remove Duplicates function in VBA.

How to Use Excel VBA Remove Duplicates?

We will learn how to use a VBA Remove Duplicates with few examples in excel.

You can download this VBA Remove Duplicates Excel Template here – VBA Remove Duplicates Excel Template

Example #1 – VBA Remove Duplicates

We have a list of numbers starting from 1 to 5 till row 20 in column A only. As we can see in the below screenshot, all the numbers are getting repeated multiple times.

VBA Duplicates example

Now our job is to remove the duplicate from the list by VBA. For this go to the VBA window by pressing the F11 key.

In this example, we will see, basic use of how VBA Remove Duplicates can work for numbers. For this, we need a Module.

Step 1: Open a new Module from the Insert menu which is in the Insert menu tab.

VBA Duplicates Module

Step 2: Once it is open write the subcategory of VBA Remove Duplicate as shown below.

Code:

Sub VBARemoveDuplicate1()

End Sub

VBA Duplicates example 1.1

Step 3: In the process of removing the duplicate, first we need to select the data. For this, in VBA we will Selection function till it goes down to select complete data list as shown below.

Code:

Sub VBARemoveDuplicate1()

Selection.End(xlDown).Select

End Sub

VBA Duplicates example 1.2

Step 4: Now we will select the Range of selected cells or columns A. It will go down till we have the data in a particular column. Not only till row 20.

Code:

Sub VBARemoveDuplicate1()

Selection.End(xlDown).Select
Range(Selection, Selection.End(xlUp)).Select

End Sub

VBA Duplicates example 1.3

Step 5: Now select the range of the cells in a currently opened sheet as shown below. This will activate the complete column. We have selected column A till the end.

Code:

Sub VBARemoveDuplicate1()

Selection.End(xlDown).Select
Range(Selection, Selection.End(xlUp)).Select
ActiveSheet.Range("A:A").

End Sub

VBA Duplicates example 1.4

Step 6: Now use RemoveDuplicate function here. This will activate the command to remove the duplicate values from the sequence of the columns 1. If there are more columns then the number will be added and separated by commas in the brackets as (1, 2, 3,…).

Code:

Sub VBARemoveDuplicate1()

Selection.End(xlDown).Select
Range(Selection, Selection.End(xlUp)).Select
ActiveSheet.Range("A:A").RemoveDuplicates Columns:=1,

End Sub

VBA Duplicates example 1.5

Step 7: Now we will use the Header command which will move the cursor to the topmost cell of the sheet, which is mostly in the header of any table.

Code:

Sub VBARemoveDuplicate1()

Selection.End(xlDown).Select
Range(Selection, Selection.End(xlUp)).Select
ActiveSheet.Range("A:A").RemoveDuplicates Columns:=1, Header:=xlYes

End Sub

VBA Duplicates example 1.6

Step 8: Now compile the code steps by pressing the F8 Key. Once done then click on the Play button to run to code as shown below.

As we can see, the duplicate number is deleted from column A and the only a unique count is left.

VBA Duplicates example 1.8

Example #2 – VBA Remove Duplicates

In this example, we will see how to remove duplicate values from more than one column. For this, we will consider the same duplicate list used in example-1. But in a new way, we have added 2 more columns of the same values as shown below.

VBA Duplicates example 2.1

This is another method with a little different type of code structure.

Step 1: Open a new module in VBA and write the subcategory in the VBA Remove Duplicate. If possible then give it a sequence number so that it will be better to choose the right code to run.

Code:

Sub VBARemoveDuplicate2()

End Sub

Dupli VBA -2

Step 2: First, select the complete sheet in VBA as shown below.

Code:

Sub VBARemoveDuplicate2()

Cells.Select

End Sub

Dupli VBA .select

Step 3: Now select the currently opened sheet with ActiveSheet command and select columns A to C as shown below.

Code:

Sub VBARemoveDuplicate2()

Cells.Select
ActiveSheet.Range("A:C").

End Sub

 Dupli VBA Range

Step 4: Now select the RemoveDuplicates command and after that select Column array from 1 to 3 as shown below.

Code:

Sub VBARemoveDuplicate2()

    Cells.Select
    ActiveSheet.Range("A:C").RemoveDuplicates Columns:=Array(1, 2, 3),

End Sub

Dupli VBA Array

Step 5: At last use, the Header command to be included in the process of removing duplicates as xlYes as shown below.

Code:

Sub VBARemoveDuplicate2()

    Cells.Select
    ActiveSheet.Range("A:C").RemoveDuplicates Columns:=Array(1, 2, 3), Header:=xlYes

End Sub

Dupli VBA Header

Step 6: Now compile the complete code and run. As we can see below, the complete sheet is selected but the duplicate values are removed from columns A, B, and C, keeping only unique count.

VBA Duplicates example 2.7

Example #3 – VBA Remove Duplicates

This is another method of removing duplicate which is the simplest way to remove duplicate in VBA. For this, we will use the data which we saw in example-1 and also shown below.

VBA Duplicates 3.1

Step 1: Now to go VBA and write subcategory again of VBA Remove Duplicates. We have given the sequence to each code we showed to have a proper track.

Code:

Sub VBARemoveDuplicate3()

End Sub

Dupli VBA 3

Step 2: This is quite a similar pattern which we have seen in example-2 but a shortcut way to write a code for removing duplicate. For this first directly start selecting the range of column as shown below. We have kept the limit till 100th cell of column A starting from 1 followed by a dot(.)

Code:

Sub VBARemoveDuplicate3()

Range("A1:A100").

End Sub

Dupli VBA Range

Step 3: Now select the RemoveDuplicates command as shown below.

Code:

Sub VBARemoveDuplicate3()

Range("A1:A100").RemoveDuplicates

End Sub

 Dupli VBA .A1:A100

Step 4: Now select the columns A as with command Columns with the sequence of 1. And after that include the Header of selected columns as well as shown below.

Code:

Sub VBARemoveDuplicate3()

Range("A1:A100").RemoveDuplicates Columns:=1, Header:=xlYes

End Sub

VBA Duplicates 3.5

Step 5: Now compile it by pressing F8 key and run. We will see our code has removed the duplicate numbers from columns A and only unique values are pertained.

VBA Duplicates 3.6

Pros of VBA Remove Duplicates

  • It is useful in quickly removing the duplicates in any range of cells.
  • It is easy to implement.
  • When working on huge data set, where removing the duplicate becomes difficult manually and it hangs the files and VBA Remove Duplicates works in a second to give us the unique values.

Cons of VBA Remove Duplicates

  • It is not beneficial to use VBA Remove Duplicates for very small data, as it could be easily done by Remove Duplicate function available in the Data menu bar.

Things to Remember

  • Range can be selected in two ways. Once it is selected the limit of cells as shown in example-1 and other is selecting the complete column till the end as shown in example-1.
  • Make sure the file is saved in Macro-Enabled Excel which will allow us to use the written code multiple time without losing it.
  • You can keep the value of function Header as Yes, as it will count the header as well while removing the duplicate values. If there is no duplicate value with the name of Headers name, then keeping it as No will harm nothing.

Recommended Articles

This has been a guide to VBA Remove Duplicates. Here we have discussed how to use Excel VBA Remove Duplicates along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA Active Cell
  2. VBA XML
  3. VBA Transpose
  4. VBA Month

Like this post? Please share to your friends:
  • Removing duplicates from excel
  • Removing duplicate in excel
  • Removing all spaces in excel
  • Removing a page from word
  • Remover для microsoft excel