Как удалить дубли в excel vba

Удаление повторяющихся значений (дубликатов) в диапазоне ячеек с помощью кода 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.

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.

Excel VBA code to remove duplicates from a given range of cells. In the below data set we have given a list of 15 numbers in “Column A” range A1:A15.  Need to remove duplicates and place unique numbers in column B.

Sample Data: Cells A1:A15

Sample Data

Final Output:

VBA Code to remove duplicates and place into next column (B)

Declare Variables:

Variables Data Type Comments
nonDuplicate Boolean It is a Boolean value (True/False).
uNo Integer Count no of Unique items in column B
colA Integer Iteration column A cells
colB Integer Iteration column B cells
'Variable Declarations
Dim nonDuplicate As Boolean, uNo As Integer, colA As Integer, colB As Integer

Always first value will be unique, So A1 place to cell B1

'Place first value to B1
Cells(1, 2).Value = Cells(1, 1).Value

Initialize variables:

'Initialize uNo = 1 since first number is already placed in column B; Assign True to the variable nonDuplicate

uNo = 1

nonDuplicate= True

Since the first number is already placed in cell B1, Loop starts from A2 to A15.  Take each number from Column A and check with Column B (unique range)

'Use for loop to check each number from A2 to A15 
For colA = 2 To 15
    For colB = 1 To uNo

if the number is already placed in column B.  Assign False to the “nonDuplicate” variable.

        If Cells(colA, 1).Value = Cells(colB, 2).Value Then
            nonDuplicate= False
        End If

“nonDuplicate” is True then place to column B and increase uNo by 1

    'if nonDuplicate is true, place cell value in column B and increase uNo = uNo + 1
    If nonDuplicate = True Then
        Cells(uNo + 1, 2).Value = Cells(colA, 1).Value
        uNo = uNo + 1
    End If

Reset “nonDuplicate” variable 

'reset nonDuplicate to True
nonDuplicate = True

Close for loop

Next colA

Implementation:

Follow the below steps to remove duplicates using Excel VBA:

Step 1: Add a shape (VBA Remove Duplicates) to your worksheet  

Step 2: Right-click on “VBA Remove Duplicates” and “Assign Macro..”

Step 3: Select “removeDuplicates”, you can see a list of macros available in your workbook

Step 4: Save your excel file as “Excel Macro-Enabled Workbook” *.xlsm

Step 5: Click “VBA Remove Duplicates” to execute VBA code and see the output

 

Добрый день! Подскажите код для удаления дубликатов строк по условию одинакового значение во всех 12 столбцах.
На данный момент применяю код

Private Sub CommandButton1_Click()

With Sheets(«Материалы»)
       Set tng = Range(«A1», Range(«l1»).End(xlDown))
       tng.RemoveDuplicates Columns:=Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12), Header:=xlYes
   End With

End Sub

но он работает только если кнопка расположена на листе «Детали», а мне нужно чтобы код работал при нажатии кнопки на форме которая запускается с другого листа.
Заранее спасибо

 

MikeVol

Пользователь

Сообщений: 230
Регистрация: 20.10.2020

Ученик

Лидия Кунакова, Доброго времени суток. Так вставьте в вашей форме кнопку далее скопируйте ваш код в форму. И самое главное когда будете кнопку вставлять на форме обратите внимание как она будет называться. И переименуйте Private Sub CommandButton1_Click() именем вашей вновь вставленной кнопки. К примеру Private Sub CommandButton8_Click(). И будет вам счастье.

 

Ігор Гончаренко

Пользователь

Сообщений: 13746
Регистрация: 01.01.1970

#3

04.12.2022 17:46:45

это

Код
Set tng = .Range("A1", .Range("l1").End(xlDown))

будет работать на листе Материалы, но что вам нужно не знаю (не смог прочитать в обьяснениях задачи)

Программисты — это люди, решающие проблемы, о существовании которых Вы не подозревали, методами, которых Вы не понимаете!

 

MikeVol

Пользователь

Сообщений: 230
Регистрация: 20.10.2020

Ученик

#4

04.12.2022 17:49:36

Ігор Гончаренко, тс скорее всего это надо

Цитата
Лидия Кунакова написал:
а мне нужно чтобы код работал при нажатии кнопки на форме

. Наверное есть некая форма уже. Выше я уже подсказал.

 

Ham13

Пользователь

Сообщений: 88
Регистрация: 02.08.2016

MikeVol, Ее код будет срабатывать на активном листе

Iгор все верно написал, чтобы срабатывало на листе Материалы (With Sheets(«Материалы»))
Нужно добавить точку
При чем тут лист Детали сложно понять, любой активный лист должен срабатывать.
Но без файла тяжело понять, может автор вообще другой смысл закладывал

 

New

Пользователь

Сообщений: 4582
Регистрация: 06.01.2013

#6

04.12.2022 18:25:10

Цитата
Лидия Кунакова написал:
Подскажите код для удаления дубликатов строк по условию одинакового значение во всех 12 столбцах.

Для получения быстрой и качественной помощи на форуме нужно всегда подготавливать небольшой файл-пример, где показать данные какие есть и можно рядом или на соседнем листе — как хочу получить. Иначе либо не получите помощь совсем, либо разговоров на месяц, либо предложенные варианты помощи вам не подойдут и т.д. и т.д. и т.д.

 

MikeVol

Пользователь

Сообщений: 230
Регистрация: 20.10.2020

Ученик

#7

05.12.2022 17:34:17

Ham13,

Цитата
Лидия Кунакова написал:
но он работает только если кнопка расположена на листе «Детали»

вам что нибудь это говорит? И да, он

Цитата
Ham13 написал:
код будет срабатывать на активном листе

так как

Цитата
Лидия Кунакова написал:
он работает только если кнопка расположена на листе «Детали»

Соответственно код запускается с активного листа потому что кнопка CommandButton1 находится на листе Детали, а сами действия происходит с листом Материалы
Но каким-то образом

Цитата
Лидия Кунакова написал:
На данный момент применяю код

даже без точки. Да тут спорный вопрос возникает без

Цитата
New написал:
небольшой файл-пример

, согласен.

 

Дмитрий(The_Prist) Щербаков

Пользователь

Сообщений: 14182
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

#8

05.12.2022 17:46:17

Цитата
MikeVol написал:
Но каким-то образом даже без точки

тут как раз все предельно ясно. Именно потому что без точки, все срабатывает на том листе, в котором код. Это действие по умолчанию для всех модулей классов — если для объекта не указан явно родитель, то в качестве родителя используется сам модуль класса. В нашем случае это сам лист. Вот и получается:
Set tng = Лист_в_котором_код.Range(«A1», Лист_в_котором_код.Range(«l1»).End(xlDown))
Если интересно, здесь расписывал все подробно и последовательно:

Как обратиться к диапазону из VBA

там много букав, но возможно, пригодится для общего понимания.

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

Дмитрий(The_Prist) Щербаков

Пользователь

Сообщений: 14182
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

#9

05.12.2022 17:50:19

Цитата
Лидия Кунакова написал:
нужно чтобы код работал при нажатии кнопки на форме которая запускается с другого листа

так и запишите свой код в виде функции с передачей нужного листа:

Код
Function RemDupes(ws as worksheet)
       Set tng = ws.Range("A1", ws.Range("l1").End(xlDown))
       tng.RemoveDuplicates Columns:=Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12), Header:=xlYes
End Function

А по кнопке с любого листа запускайте:

Код
Private Sub CommandButton1_Click()
'передаем в функцию лист с именем "Материалы". Именно в нем будут удалены дубликаты
Call RemDupes(Sheets("Материалы"))
End Sub

Или если надо удалять дубли на листе «Детали»:

Код
Private Sub CommandButton1_Click()
'передаем в функцию лист с именем "Детали". Именно в нем будут удалены дубликаты
Call RemDupes(Sheets("Детали"))
End Sub

Изменено: Дмитрий(The_Prist) Щербаков05.12.2022 17:51:11

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

Всем большое спасибо! Помогло. Когда вносила корректировки в код забыла про Range(«l1») . Дмитрий, вам также спасибо за ссылку на статью, я обязательно ознакомлюсь.

 

MikeVol

Пользователь

Сообщений: 230
Регистрация: 20.10.2020

Ученик

#11

10.12.2022 21:11:02

Лидия Кунакова, Вот это вы Оперативно отвечаете на свои темы… Не прошло и пол года…

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,2393 gold badges32 silver badges57 bronze badges

Понравилась статья? Поделить с друзьями:

А вот еще интересные статьи:

  • Как удалить дробную часть в excel
  • Как удалить встроенный word
  • Как удалить дату создания содержимого word
  • Как удалить выпадающее меню в excel
  • Как удалить документы word на андроиде

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии