加快Excel VBAsearch脚本

我需要search重复值并在Excel电子表格中将其标记。 我有我的数据来validation列D和数据在可能重复在列K 。 我需要检查列D每一行所有行中的列。 K

这是我目前的脚本:

 Sub MySub() Dim ThisCell1 As Range Dim ThisCell2 As Range For Each ThisCell1 In Range("D1:D40000") 'This is the range of cells to check For Each ThisCell2 In Range("K1:K40000") 'This is the range of cells to compare If ThisCell1.Value = ThisCell2.Value Then If ThisCell1.Value <> "" Then ThisCell1.Interior.ColorIndex = 3 End If Exit For End If Next ThisCell2 Next ThisCell1 End Sub 

这个问题是非常缓慢的。 我的意思是检查数据是不能接受的。 即使范围设置为1:5000 ,也需要10-15分钟才能完成。 有什么办法可以让它更快?

字典将是最快的方式来实现你正在寻找的东西。 不要忘记在项目中添加对“Microsoft脚本运行时”的引用

 Sub MySubFast() Dim v1 As Variant Dim dict As New Scripting.Dictionary Dim c As Range v1 = Range("D1:D40000").Value For Each c In Range("K1:K40000") If Not dict.Exists(c.Value) Then dict.Add c.Value, c End If Next Dim i As Long For i = LBound(v1, 1) To UBound(v1, 1) If v1(i, 1) <> "" Then If dict.Exists(v1(i, 1)) Then Range("D" & i).Interior.ColorIndex = 3 End If End If Next i End Sub 

注意:这是@Jeanno回答的改进。

使用数组而不是引用对象(范围)的方式更快。

 Sub MySubFast() Dim v1 As Variant Dim v2 As Variant v1 = Range("D1:D40000").Value v2 = Range("K1:K40000").Value Dim i As Long, j As Long For i = LBound(v1, 1) To UBound(v1, 1) For j = LBound(v2, 1) To UBound(v2, 1) If v1(i, 1) = v2(j, 1) Then If v1(i, 1) <> "" Then Range("D" & i).Interior.ColorIndex = 3 End If Exit For End If Next j Next i End Sub 

如果列K中存在值,是不是只突出显示D列中的单元格? 不需要VBA,只需使用条件格式。

  • select列D(select整个列是好的)
  • 使用以下公式添加条件格式: =COUNTIF($K:$K,$D1)>0

当您更改D和K列中的数据时,条件格式将自动应用和更新,并且基本上应该是即时的