Link to home
Start Free TrialLog in
Avatar of nainil
nainilFlag for United States of America

asked on

Find and count duplicates in Excel using Macro / vba

I have an excel sheet with multiple columns. What I want to do is:

Scan Column B
Find duplicates
Highlight duplicates in Yellow (or any color)
Provide a count of the duplicate values (Yellow highlighted).

I have the below code. It highlights the cells as soon as I enter and filters duplicates.

I would want to have the filtering happen only after user clicks on a button. Ofcourse, I would like to have a count of these duplicates as well.

 
Sub ValidateData()

    If (ActiveSheet.Name = "Codes") Then
        MsgBox ("HHHHIII")
        Sheets("Codes").Columns("B:B").Select
        Selection.FormatConditions.AddUniqueValues
        Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
        Selection.FormatConditions(1).DupeUnique = xlDuplicate
        With Selection.FormatConditions(1).Interior
            .PatternColorIndex = xlAutomatic
            .Color = 65535
            .TintAndShade = 0
        End With
        Selection.FormatConditions(1).StopIfTrue = True

        
'        ActiveSheet.Range("Q18").HorizontalAlignment = xlCenter
'        ActiveSheet.Range("Q18").Value = cntDuplicates
'        ActiveSheet.Range("Q18").AddComment(str + " contain duplicates").Shape.TextFrame.AutoSize = True
        
'        str = ""
'        cntDuplicates = 0
        ActiveSheet.Range("A1").Select
    End If
   
End Sub

Open in new window

SOLUTION
Avatar of ukerandi
ukerandi
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of nainil

ASKER

@ukerandi:

This is excellent. I am trying to understand the code as to what it does and how is it getting duplicates.

I see how the counts happen (i think), but, I am not sure what you have used to find the duplicates.

The solution is terrific and i believe it works as expected, but just curious on how it works.
hi i'm using Countif Function to find out how many same records available in the Range. if any records more than 1 it will color the cell.
Example
A                      B
test                12
test1               2
test3
test 4

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial