Excel VBA Highlight duplicates in active column

后端 未结 1 1208
生来不讨喜
生来不讨喜 2021-01-14 23:04

I\'m trying to create a macro that will highlight duplicates in the column where text is being entered.

I have 54 columns and want to highlight duplicates in each c

相关标签:
1条回答
  • 2021-01-14 23:17

    Try this one:

    Set Rng = Range(Cells(1, Target.Column), Cells(Rows.Count, Target.Column).End(xlUp))
    

    and it's better to use Worksheet_Change event instead Worksheet_SelectionChange.

    Btw, there is special CF for duplicates:

    enter image description here


    UPD: If you'd like to use VBA, try following code:

    Private Sub Worksheet_Change(ByVal Target As Range)
    
        Dim Rng As Range
        Dim cel As Range
        Dim col As Range
        Dim c As Range
        Dim firstAddress As String
    
    
    
        'Duplicates will be highlighted in red
        Target.Interior.ColorIndex = xlNone
        For Each col In Target.Columns
            Set Rng = Range(Cells(1, col.Column), Cells(Rows.Count, col.Column).End(xlUp))
            Debug.Print Rng.Address
    
            For Each cel In col
                If WorksheetFunction.CountIf(Rng, cel.Value) > 1 Then
                    Set c = Rng.Find(What:=cel.Value, LookIn:=xlValues)
                    If Not c Is Nothing Then
                        firstAddress = c.Address
                        Do
                            c.Interior.ColorIndex = 3
                            Set c = Rng.FindNext(c)
                        Loop While Not c Is Nothing And c.Address <> firstAddress
                    End If
                End If
            Next
        Next col
    
    End Sub
    
    0 讨论(0)
提交回复
热议问题