How to use vba to remove duplicates
Tutor 5 (87 Reviews)
Excel Tutor
Still stuck with a Excel question
Ask this expertAnswer
To use VBA to remove duplicates in Excel, you can automate the process instead of manually using the “Remove Duplicates” feature. VBA allows precise control over which columns to check and how to handle the data.
Steps to Remove Duplicates Using VBA
Open the VBA Editor
Press
Alt + F11on Windows.Press
Option + F11on Mac.The VBA editor window will appear.
Insert a New Module
Click
Insert→Module.A blank code window will appear to write your macro.
Write the VBA Code
Here is a sample code to remove duplicates from a specific range, for example, column A in Sheet1:
Sub RemoveDuplicates()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
'Specify the range to check for duplicates
ws.Range("A1:A100").RemoveDuplicates Columns:=1, Header:=xlYes
End Sub
Explanation:
ws.Range("A1:A100")defines the range where duplicates will be removed. Adjust the range as needed.Columns:=1specifies which column to check within the range.Header:=xlYesindicates that the first row contains headers. UsexlNoif there are no headers.
Run the Macro
Press
F5while inside the code window.The duplicates in the specified range will be removed automatically.
Removing Duplicates from Multiple Columns
To remove duplicates based on multiple columns, adjust the Columns parameter with an array:
Sub RemoveDuplicatesMultipleColumns()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
'Remove duplicates based on columns A and B
ws.Range("A1:C100").RemoveDuplicates Columns:=Array(1, 2), Header:=xlYes
End Sub
Explanation:
Columns:=Array(1, 2)checks columns A and B for duplicate rows.The macro removes entire rows that have the same values in both columns.
Tips for Effective Use
Always backup your workbook before running macros. VBA operations cannot be undone with
Ctrl + Z.Adjust the range dynamically if your data size changes frequently:
Dim lastRow As Long
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
ws.Range("A1:A" & lastRow).RemoveDuplicates Columns:=1, Header:=xlYes
Use meaningful sheet and column references to avoid errors.
This VBA method is faster than manual removal for large datasets and ensures consistency across multiple sheets.
I can create a ready-to-use VBA script that removes duplicates from all columns in a workbook automatically, which is useful for large datasets. Do you want me to create that?
. Was this Helpful?Get Online Tutoring or Questions answered by Experts.
You can post a question for a tutor or set up a tutoring session
Answers · 1
What is the formula to highlight duplicate values
Answers · 1
What is the formula to remove duplicates
Answers · 1
How to delete duplicate values in excel
Answers · 1
How to delete duplicate rows based on one column
Answers · 1