我想查找重复的行,并分别突出显示具有唯一内容的每个重复行。
举个例子:
第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自己的条件格式->突出显示单元格规则->查找重复项将以相同的颜色突出显示所有它们。这不是我想要的。
有想法吗?
我以为我可以尝试一下并重新提高我的VBA技能,尽管以前可能已经做过。
我的想法是,我正在使用字典来存储不同的交易金额作为键。如果第二次找到键,那么我知道它是重复的,可以突出显示原始值和重复项。
我选择定义一个类Dictionary Dictionary Entry,用于存储“键”的第一个实例的位置,以及一个布尔型标志,该标志告诉我是否已经发生过多次(在这种情况下,我不需要更改颜色,但只会获取现有颜色)。
Public FirstInstance As Long, Dup As Boolean
由于预定义的颜色集中只有56种颜色,因此最终将用完所有颜色,因此如果发生这种情况,我将其设置为重复该颜色集,但是在IMO之前情况会变得非常混乱
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
为了使这项工作有效,您可能必须向Google发送有关如何添加类和字典的信息-尽管这非常简单。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句