VBA macros · Formatting
VBA macro to highlight duplicate values in Excel
Colour every cell in the selection whose value appears more than once. Works on Windows and Mac, plus a one-line conditional formatting alternative.
Before you remove duplicates you usually want to see them: which invoice numbers appear twice, which email addresses are repeated. This macro gives every duplicate cell in the selection a light red fill and counts them. Unlike conditional formatting, the colour stays put when the data is copied elsewhere or filtered by colour.
Option Explicit
Sub HighlightDuplicates()
Dim rng As Range, c As Range
Dim counts As Collection
Dim k As String
Dim n As Long, dupCells As Long
If TypeName(Selection) <> "Range" Then Exit Sub
Set rng = Intersect(Selection, Selection.Worksheet.UsedRange)
If rng Is Nothing Then Exit Sub
Set counts = New Collection
Application.ScreenUpdating = False
' Pass 1: count how often each value occurs
For Each c In rng.Cells
If Not IsError(c.Value) Then
k = CStr(c.Value)
If Len(k) > 0 Then
n = KeyCount(counts, k)
If n > 0 Then counts.Remove k
counts.Add n + 1, k
End If
End If
Next c
' Pass 2: colour the cells whose value occurs more than once
For Each c In rng.Cells
If Not IsError(c.Value) Then
k = CStr(c.Value)
If Len(k) > 0 Then
If KeyCount(counts, k) > 1 Then
c.Interior.Color = RGB(255, 199, 206)
dupCells = dupCells + 1
End If
End If
End If
Next c
Application.ScreenUpdating = True
MsgBox dupCells & " duplicate cell(s) highlighted.", vbInformation
End Sub
Private Function KeyCount(col As Collection, ByVal key As String) As Long
' Returns the stored count, or 0 when the key is not in the collection
On Error Resume Next
KeyCount = col(key)
End FunctionHow to use it
- Open the workbook and press
Alt+F11(Mac:Opt+F11orFn+Opt+F11) to open the VBA editor. See The Developer tab and the VBA editor if you have never used it. - Choose Insert › Module. An empty code window opens on the right.
- Paste the whole code into that window. If the module already starts with
Option Explicit, do not paste that line twice. - Go back to Excel, press
Alt+F8(Mac:Opt+F8, or Tools › Macro › Macros), pickHighlightDuplicatesand click Run. - Select the cells to check (one column or a block) before running.
- Save the file as an Excel Macro-Enabled Workbook (.xlsm). A normal .xlsx file throws the code away when you save it.
To have this macro ready in every workbook, keep it in your Personal Macro Workbook (PERSONAL.XLSB). If you do not have one yet, record any tiny macro with Store macro in: Personal Macro Workbook (see The macro recorder: record, read and clean up code), then paste this code into a module under VBAProject (PERSONAL.XLSB). The macro works on whichever workbook is active when you run it.
How it works
The macro works in two passes. In the first pass it counts every value. It stores the counts in a Collection, using the value as the key; a Collection can look up an item by key almost instantly. Collection items cannot be changed in place, so to increase a count the old item is removed and re-added with the new number. Collections are introduced in Collections and dictionaries in VBA.
KeyCount asks the collection for a key with errors switched off. If the key does not exist, the lookup fails, the assignment is skipped and the function returns its default value, 0.
In the second pass every cell whose count is above 1 gets the fill RGB(255, 199, 206), the same light red Excel uses for its built-in duplicate rule. Both the first and later occurrences are coloured. Empty cells and error values are skipped. Limiting the selection to the used range with Intersect means selecting a whole column does not loop through a million empty cells.
Change it
If you prefer a live highlight that updates when the data changes, add a conditional formatting rule instead. These lines do the same as Home › Conditional Formatting › Highlight Cells Rules › Duplicate Values:
Sub HighlightDuplicatesLive()
With Selection.FormatConditions.AddUniqueValues
.DupeUnique = xlDuplicate
.Interior.Color = RGB(255, 199, 206)
End With
End SubTo colour only the second and later occurrences, so the first one stays plain, combine the passes: count while looping, and colour the cell as soon as KeyCount is already 1 or more before adding it. To remove the highlight later, select the cells and use Home › Fill Color › No Fill, or run Selection.Interior.Pattern = xlNone. Once you have checked the duplicates, delete them with VBA macro to remove duplicates based on one column in Excel.
What can go wrong
Collection keys ignore upper and lower case, so Apple and apple count as duplicates. That matches how Excel's own duplicate tools behave. Values are compared as text, so the number 5 and the text 5 count as the same value, while 5 and 5.0 typed as text do not. Leading or trailing spaces make values different; clean them with VBA macro to trim spaces in selected cells in Excel first.
Related: VBA macro to remove duplicates based on one column in Excel, VBA function to count cells by background color in Excel.