我有两张非常大的桌子。其中一个有12列和280K行。其他的有12k rowns和33列。我正在使用vlookup来查找大表中的匹配值到小表。 Vlookups需要永远计算。使用VBA代码有一种简单的方法吗?有人可以共享示例代码供我复制吗?
由于
答案 0 :(得分:0)
您可以使用Collection
对象快速查找匹配项。这将非常快(如果不比VLOOKUP
更快),因为当您将关键参数添加到Collection
时 - 它会将其值与最后快速查找的特定目标进行哈希/索引。)
此外,对于大量记录,您填充Collection
一次并继续重复使用它,而VLOOKUP
会重复搜索整个目标范围(虽然内置公式运行,效率会降低在多个核心上并行加上微软内置一些缓存以提高重复搜索的效率。即使这样,单线程VBA集合仍然应该更快。
请参阅下面的示例,并在内联评论中提供更多信息。
“大表”在Sheet1上:
“小表”在Sheet2上:
将小表中的记录与大表中的记录匹配的代码:
Option Explicit
Sub matchRows()
' this is where the big table is
Dim w1 As Worksheet
Set w1 = Worksheets("Sheet1")
' this is where the small table is
Dim w2 As Worksheet
Set w2 = Worksheets("Sheet2")
Dim c As New Collection ' list of match keys in big table 1
Dim r As Range
' assume the match key is in col1 in both tables
' enumerate the keys in the big table
For Each r In w1.Range(w1.[a2], w1.[a2].End(xlDown))
c.Add r, r ' this stores the range (first param) and
' its key (second param - taken as string
' (value of the range), must be unique)
Next r
' now lets try to match / vlookup records in small table against
' big table
For Each r In w2.Range(w2.[a2], w2.[a2].End(xlDown))
If contains(c, CStr(r)) Then
' you didn't say what you want to do after a match, so
' I'll just display matched key value and row number in debug console
Debug.Print "Found match """ & r & """ at row number " & r.Row
Else
Debug.Print "No match found for """ & r & """ at row number " & r.Row
End If
Next r
End Sub
Function contains(col As Collection, key As String) As Boolean
On Error Resume Next
col.Item key
contains = (Err.Number = 0)
On Error GoTo 0
End Function
立即窗口中的结果:
Found match "data51" at row number 2
Found match "data61" at row number 3
No match found for "data81" at row number 4
Found match "data91" at row number 5