2015-02-05 98 views
2

我需要搜索重复值并将它们标记在Excel电子表格中。我有我的数据在列D中进行验证,并且在可能的情况下重复的数据位于列K中。我需要检查列中所有行的D列中的每一行。 K加快Excel VBA搜索脚本

这是我为这个当前脚本:

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分钟才能完成。有什么办法可以让它更快吗?

+0

你如何定义你的搜索?您是否检查列D中的值是否出现在列K中?还是它不得不多次出现在K列中? – user3561813 2015-02-05 16:29:44

+0

我正在检查'K'列中的值是否出现在列'D'中。在'D'列中可能有多个出现,所以这就是为什么搜索必须检查'D'中每行的'K'中的所有行。 – PeterInvincible 2015-02-05 16:32:52

回答

1

字典将是最快的方式来实现你在找什么。不要忘记在您的项目中添加对“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答案的改进。

+0

谢谢,按预期工作。 :) – PeterInvincible 2015-02-05 18:40:58

+0

你有多少加速? – Seb 2015-02-05 19:11:28

+0

我的脚本在D列中有13行,在K列中有4.5k,需要超过2小时才能完成。你的版本花了6分钟:)) – PeterInvincible 2015-02-05 22:16:51

1

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

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 
+0

这很有用,谢谢! – PeterInvincible 2015-02-05 18:41:20

1

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

  • 选择列d(选择整列是罚款)
  • 使用此公式添加条件格式:=COUNTIF($K:$K,$D1)>0

条件格式将应用和自动更新为您更改列的数据d和K,它应该基本上是即时的