我想用这个来测试一下我的技能,尽管@matzone 已经给出了确切的答案。我做了这个完全一样的Sub,但是使用了Range
对象和.Find()
方法。有评论...
Private Sub Test()
FindAndColorMatchesOfTwoColumns "A", "B"
End Sub
Private Sub FindAndColorMatchesOfTwoColumns(colTarget As String, colList As String)
Dim rLookUp As Range ' Column range for list compared against
Dim rSearchList As Range ' Column range for compare items
Dim rMatch As Range
Dim sAddress As String
' Set compared against list from colTarget column
Set rLookUp = Range(colTarget & "1:" & _
colTarget & Range(colTarget & "1").End(xlDown).Row)
' Loop trough list from colList column
For Each rSearchList In Range(colList & "1:" & colList & Range(colList & "1").End(xlDown).Row)
' Find for a match
Set rMatch = rLookUp.Find(rSearchList.Value, LookAt:=xlWhole)
If Not rMatch Is Nothing Then
' Store first address found
sAddress = rMatch.Address
' Loop trough all matches using .FindNext,
' exit if found nothing or address is first found
Do
' Set the color
rMatch.Font.Color = vbRed
Set rMatch = rLookUp.FindNext(rMatch)
Loop While Not rMatch Is Nothing And rMatch.Address <> sAddress
End If
Next
Set rMatch = Nothing
Set rSearchList = Nothing
Set rLookUp = Nothing
End Sub
这个想法是更加动态,接受两列作为参数,设置搜索范围直到Range.End(xlDown).Row
而不是固定计数。循环槽也只匹配。
对于原始问题,简单的.Cells()
嵌套循环要简单得多,但是.Find()
如果列数达到数千,则使用会更快。
用这个测试子测试了“长列表”假设:
Private Sub RunTest()
Dim tStart As Date
Dim tEnd As Date
tStart = Timer
FindAndColorMatchesOfTwoColumns "A", "B"
tEnd = Timer
Debug.Print Format(tEnd - tStart, "0.000")
tStart = Timer
Test
tEnd = Timer
Debug.Print Format(tEnd - tStart, "0.000")
End Sub
将 1500 行添加到 A 列,将 184 行添加到 B 列并获得即时视图结果:
0,266
12,719
因此,性能确实存在巨大差异……如果 OP 仅提供简单的问题示例并打算在更大的数据集中使用它。