Macro 56: Highlight Duplicates in a Range of Data
Ever wanted to expose the duplicate values in a range? The macro in this section does just that. There are
many manual ways to find and highlight duplicates — ways involving formulas, conditional for- matting,
sorting, and so on. However, all these manual methods take setup and some level of main- tenance as the
data changes. This macro simplifies the task, allowing you to find and highlight duplicates in your data
with a click of the mouse.
How it works
This macro enumerates through the cells in the target range, leveraging the For Each statement to
activate each cell one at a time. We then use the CountIf function to count the number of times
the value in the active cell occurs in the range selected. If that number is greater than one, we format
the cell yellow.
Sub Macro56()
‘Step 1: Declare your variables
Dim MyRange As Range
Dim MyCell As Range
‘Step 2: Define the target Range.
Set MyRange = Selection
‘Step 3: Start looping through the range.
For Each MyCell In MyRange
‘Step 4: Ensure the cell has Text formatting.
If WorksheetFunction.CountIf(MyRange, MyCell.Value) > 1
Then MyCell.Interior.ColorIndex = 36
End If
‘Step 5: Get the next cell in the range
Next MyCell
End Sub
1. Step 1 declares two Range object variables, one called MyRange to hold the entire target
range, and the other called MyCell to hold each cell in the range as the macro enumerates
through them one by one.
2. Step 2 fills the MyRange variable with the target range. In this example, we are using the
selected range — the range that was selected on the spreadsheet. You can easily set the
MyRange variable to a specific range such as Range(“A1:Z100”). Also, if your target
range is a named range, you can simply enter its name: Range(“MyNamedRange”).
3. Step 3 starts looping through each cell in the target range, activating each cell.
4. The WorksheetFunction object provides a way for us to be able to run many of Excel’s
spreadsheet functions in VBA. Step 4 uses the WorksheetFunction object to run a
CountIf function in VBA.
In this case, we are counting the number of times the active cell value (MyCell.Value) is
found in the given range (MyRange). If the CountIf expression evaluates to greater than 1,
the macro changes the interior color of the cell.
5. Step 5 loops back to get the next cell. After all cells in the target range are activated, the
macro ends.
How to use it
To implement this macro, you can copy and paste it into a standard module:
1. Activate the Visual Basic Editor by pressing ALT+F11 on your keyboard.
2. Right-click the project/workbook name in the Project window.
3. Choose Insert➜Module.
4. Type or paste the code.