Highlight duplicates across a workbook

后端 未结 2 532
无人及你
无人及你 2021-01-20 04:48

I am trying to highlight duplicates across a workbook of 12 sheets.

We track ID#s and I want to highlight the cell if an ID# (value) is on any of the other sheets.

2条回答
  •  半阙折子戏
    2021-01-20 05:36

    Here is a simplified example that should give you some ideas and point you in the right direction. If you have an questions, let me know.

    Sub collected_ids_example()
        ' enable microsoft scripting runtime --> tools - references
        ' For convenience I put all code in 2 subs/functions
        ' This code assumes you want every cell with a duplicate id highlighted.
        ' Although it is easy enough to modify that if you want.
    
        Dim sh As Worksheet
        Dim id_to_addresses As New Dictionary
        Dim id_ As Range
    
        ' For every worksheet collect all ids and their associated adressses
        ' for the specified range.
        For Each sh In ThisWorkbook.Sheets
            For Each id_ In sh.Range("A4:A100")
                If Not IsEmpty(id_) Then
                    If Not id_to_addresses.Exists(id_.Value) Then
                        Set id_to_addresses(id_.Value) = New Collection
                    End If
                    id_to_addresses(id_.Value).Add get_full_address(id_)
                End If
            Next id_
        Next sh
    
        ' Color each cell with a duplicate id
        Dim collected_id As Variant
        Dim adresses As Collection
        Dim c As Range
        For Each collected_id In id_to_addresses
            Dim duplicate_address As Variant
            Set adresses = id_to_addresses(collected_id)
    
            'You have a duplicate if an id is associated with more than 1 addrress
            If adresses.Count >= 2 Then
                For Each duplicate_address In adresses
                    Set c = Range(duplicate_address)
                    c.Interior.ColorIndex = 3
                Next duplicate_address
            End If
        Next collected_id
    End Sub
    
    Private Function get_full_address(c As Range) As String
        get_full_address = "'" & c.Parent.Name & "'!" & c.Address(External:=False)
    End Function
    

提交回复
热议问题