《神奇的VBA》编程:标识重复数据

------ 需求案例------
日常办公场景中经常会有标识重复数据的需求,如:
标识某列中是否有重复订单号
标识某个选区中的重复值等等
本篇《神奇的VBA》编程将提供几种思路。

思路1: 利用Excel原生功能
Ms Excel软件中自带"条件格式"--> "突出显示单元格规则(H)"-->"重复值(D)"功能,该功能可以快速凸显选区内的所有重复值。


通过Excel自带的功能,很轻松地解决了需求。

思路2: 通过录制宏将Excel原生功能转化为灵活复用的宏代码
在办公自动化的应用中,我们可以借助录制宏的功能,将"条件格式"--> "突出显示单元格规则(H)"-->"重复值(D)"功能转化为宏代码(见下面代码),稍加改动就可以轻松复用。
Sub 宏1()Dim rng As RangeSet rng = Application.Intersect(Columns("D:D"), ActiveSheet.UsedRange)With rng .FormatConditions.AddUniqueValues .FormatConditions(rng.FormatConditions.Count).SetFirstPriority .FormatConditions(1).DupeUnique = xlDuplicate .FormatConditions(1).Font.Color = -16383844 .FormatConditions(1).Interior.Color = 13551615 .FormatConditions(1).StopIfTrue = FalseEnd WithSet rng = NothingEnd Sub
思路3: 利用遍历循环+字典
我们也可以利用常规的For Each遍历循环和字典("Scripting.Dictionary")功能实现同等的功能。
Sub 标识重复项1()Application.ScreenUpdating = FalseDim rng As RangeDim dic As Object
Set rng = Application.Intersect(Columns("D:D"), ActiveSheet.UsedRange)Set dic = CreateObject("Scripting.Dictionary")'遍历单元格区域,统计重复数据数量并存放进字典For Each c In rng If c <> "" Then c.Interior.Color = xlNone dic(c.Value) = dic(c.Value) + 1 End IfNext
'再次遍历单元格区域,根据字典统计数据,有重复的则变色处理For Each c In rng If dic(c.Value) > 1 Then c.Font.Color = -16383844 c.Interior.Color = 13551615 End IfNext
Set dic = NothingSet rng = NothingApplication.ScreenUpdating = TrueEnd Sub有关遍历循环和字典功能更多详细说明请下载安装《神奇的VBA》插件学习。
在本篇案例的基础上,如果将需求再提升一个难度,比如使用颜色标识选区中的多余的重复值,怎么处理呢?
例如:重复值中,第一个重复值标识为黄色, 其它标识为红色。
本篇《神奇的VBA》将继续综合运用Excel VBA编程中常见的遍历循环和字典功能方法来实现这个需求。
Sub 标识重复项()Application.ScreenUpdating = FalseDim rng As RangeDim dic As Object
Set rng = Application.Intersect(Columns("D:D"), ActiveSheet.UsedRange)Set dic = CreateObject("Scripting.Dictionary")
'遍历单元格区域,统计重复数据数量并存放进字典For Each c In rng If c <> "" Then c.Interior.Color = xlNone dic(c.Value) = dic(c.Value) + 1 End IfNext
'再次遍历单元格区域,根据字典统计数据,有重复的则变色处理For Each c In rng If dic(c.Value) > 1 Then c.Interior.Color = vbYellow dic(c.Value) = -1 ElseIf dic(c.Value) = -1 Then c.Font.Color = -16383844 c.Interior.Color = 13551615 End IfNext
Set dic = NothingSet rng = NothingApplication.ScreenUpdating = TrueEnd Sub注意代码中dic(c.Value) = -1对于代码后续执行有至关重要的作用。用来标识该重复值是否已经经过处理了。

今天的分享就到这里,本篇中介绍的思路抛砖引玉,如果您有更多更好的思路欢迎分享!
赞 (0)
