查找并突出显示Excel

时间:2016-10-22 07:54:10

标签: excel duplicates

我想找到重复的行,并分别突出显示每个具有唯一内容的重复行

举个例子:

第1行 - '交易$ 44.20'

第25行 - '交易$ 44.20'

第31行 - '交易$ 57.40'

第46行 - '交易$ 57.40'

第54行 - '交易$ 57.40'

第156行 - '交易$ 15.90'

第197行 - '交易$ 15.90'

如您所见,有三组重复 - 第1行和第25行,第31,46和54行以及第156和197行,而每个重复内容都是唯一的。

我想找到并突出显示所有这些独特但重复的条目集,每个集都有不同的颜色。所以行1,25 - 一种颜色,行31,46,54 - 另一行,行156,197 - 第三,依此类推。

Excel自己的条件格式 - >突出显示单元格规则 - >查找重复项将使用相同的颜色突出显示所有这些。这不是我想要的。

想法?

1 个答案:

答案 0 :(得分:0)

我以为我已经开始了,并且稍微提高了我的VBA技能,尽管之前可能已经完成了。

我的想法是,我使用字典将不同的交易金额存储为关键字。如果第二次找到某个密钥,那么我知道它是重复的,可以突出显示原始值和重复。

我选择定义一个类词典条目,它存储'键的第一个实例的位置,加上一个布尔标志,告诉我它是否已经多次出现过(在这种情况下,我不需要更改颜色,但只会检索现有的颜色)。

Public FirstInstance As Long, Dup As Boolean

由于预定义的颜色集中只有56种颜色,这最终会耗尽颜色,所以如果发生这种情况,我会将其设置为重复颜色集,但在此之前,事情会变得相当混乱

Sub HighlightDups()
Dim MyDictionary As Scripting.Dictionary
Set MyDictionary = New Scripting.Dictionary
Dim MyDictionaryEntry As DictionaryEntry
Dim MyColour, palette As Integer
Dim I, LastRow As Long
Dim contents As Single
palette = 2

With ActiveSheet
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With

With MyDictionary
For i = 1 To LastRow
    contents = Cells(i, 1)
    If Not .Exists(contents) Then
        ' New key - create entry
        Set MyDictionaryEntry = New DictionaryEntry
        MyDictionaryEntry.FirstInstance = i
        .Add contents, MyDictionaryEntry
    Else
        If Not .Item(contents).Dup Then
            ' Dup not previously found - set new colour
            palette = palette + 1
            If palette > 56 Then palette = 2
            .Item(contents).Dup = True
            Cells(i, 1).Interior.ColorIndex = palette
            Cells(.Item(contents).FirstInstance, 1).Interior.ColorIndex = palette

        Else
            'Dup already found - retrieve previous colour
            MyColour = Cells(.Item(contents).FirstInstance, 1).Interior.ColorIndex
            Cells(i, 1).Interior.ColorIndex = MyColour
        End If
    End If
Next i
End With

End Sub

你可能需要谷歌如何添加一个类和一个字典才能使这项工作 - 但它很简单。

enter image description here