How to remove duplicates excel vba
Tutor 5 (87 Reviews)
Excel Tutor
Still stuck with a Excel question
Ask this expertAnswer
To remove duplicates in Excel using VBA, you can use the RemoveDuplicates method, which is part of the Range object. This method allows you to delete duplicate rows based on one or multiple columns efficiently.
Step-by-Step Guide
Open the VBA Editor
PressAlt + F11to open the Visual Basic for Applications (VBA) editor.Insert a New Module
Click
Insert→Module.A blank module appears where you can write your code.
Write the VBA Code
The basic syntax of theRemoveDuplicatesmethod is:Range("YourRange").RemoveDuplicates Columns:=Array(ColumnNumbers), Header:=xlYes
Explanation:
YourRange: The range where you want to remove duplicates (e.g.,"A1:C100").Columns: An array of column numbers to check for duplicates. For example,Array(1,2)will check duplicates in the first two columns.Header: UsexlYesif your range contains headers,xlNoif it does not.
Example Code
Suppose you have data inA1:C100and you want to remove duplicates based on columns A and B:Sub RemoveDuplicatesExample()
' Remove duplicates based on columns A and B
Range("A1:C100").RemoveDuplicates Columns:=Array(1, 2), Header:=xlYes
End Sub
Run the Macro
Press
F5while in the VBA editor or go back to Excel →Developer→Macros→ selectRemoveDuplicatesExample→Run.Excel will remove duplicate rows according to the columns specified.
Notes and Best Practices
The
Columnsparameter refers to the position of columns in your selected range, not necessarily the column letters in the sheet.Always make a backup of your data before running the macro because duplicates will be permanently deleted.
For dynamic ranges, you can use VBA to determine the last row automatically:
Sub RemoveDuplicatesDynamic()
Dim LastRow As Long
LastRow = Cells(Rows.Count, "A").End(xlUp).Row
Range("A1:C" & LastRow).RemoveDuplicates Columns:=Array(1, 2), Header:=xlYes
End Sub
To remove duplicates across a single column only, you can simplify the
Columnsparameter:Range("A1:A100").RemoveDuplicates Columns:=1, Header:=xlYes
On Mac, VBA syntax for
RemoveDuplicatesis identical, but keyboard shortcuts to access the VBA editor differ (Option + F11for Mac).
This approach is ideal for large datasets where using the Excel ribbon manually would be inefficient.
Get Online Tutoring or Questions answered by Experts.
You can post a question for a tutor or set up a tutoring session
Answers · 1
How to show duplicates in red
Answers · 1
How to apply duplicate conditional formatting rule
Answers · 1
How to duplicate conditional formatting excel
Answers · 1
What is excel conditional formatting duplicates
Answers · 1