excelvba

Find duplicates in each column separately


I have a spreadsheet that has data in columns C thru P.
Each column will have the data points that are the same. I want to highlight a duplicate value in a column.

Example:

Col C Col D Col E
Brad Brad Brad
Ted Ted Mike
Brad Mike Ted
Mike Phil Mike

I would like to highlight Brad in Col C, nothing in Col D and Mike in Col E.
Note the data from Col C will be copied and pasted across Col D thru P.

I tried conditional formatting and it would only work until I copied and pasted cells.

This code works for Col C. I was unable to expand it to work for each column.

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    
    If Target.Row = 2 Then Exit Sub
    
    On Error GoTo ErrHandler
    Application.ScreenUpdating = False
    
    Dim xRng1 As Range
    Dim xRng2 As Range
    
    Set xRng1 = Range("C14:C" & Cells(Rows.Count, "C").End(xlUp).Row)
    
    For Each xRng2 In xRng1
        xRng2.Offset(0, 0).Font.Color = vbBlack
        
        If Application.Evaluate("COUNTIF(" & xRng1.Address & "," & xRng2.Address & ")") > 1 Then
            xRng2.Offset(0, 0).Font.Color = vbRed
        End If
    Next xRng2
    
    Set xRng1 = Nothing
    
ErrHandler:
    Application.EnableEvents = True
    Application.ScreenUpdating = True
    
End Sub

Solution

  • Since you are using the Worksheet_Change event to find which cell was triggered, all you need to modify is the way you set-up your xRng1 object to Target.

    Modified Code

    Option Explicit
      
    Private Sub Worksheet_Change(ByVal Target As Range)
        
        Dim xRng1 As Range, xRng2 As Range
        Dim LastRow As Long
        
        If Target.Row = 2 Then Exit Sub
        
        On Error GoTo ErrHandler
        Application.ScreenUpdating = False
        
        LastRow = Cells(Rows.Count, Target.Column).End(xlUp).Row
        ' set-up range object using the Column that was triggered 
        Set xRng1 = Range(Cells(14, Target.Column), Cells(LastRow, Target.Column))
        
        For Each xRng2 In xRng1
            xRng2.Offset(0, 0).Font.Color = vbBlack
            
            If Application.Evaluate("COUNTIF(" & xRng1.Address & "," & xRng2.Address & ")") > 1 Then
                xRng2.Offset(0, 0).Font.Color = vbRed
            End If
        Next xRng2
        
        Set xRng1 = Nothing
        
    ErrHandler:
        Application.EnableEvents = True
        Application.ScreenUpdating = True
        
    End Sub