|
当需要匹配的数据几十万行时,vlookup函数运行很卡,用VBA字典可以解决。字典法的dlookup函数,不足之处是只能在同一个工作表里面使用。代码如下:
- Sub dlookup()
- Dim i&, arr1(), arr2(), krr(), temp(), t&, s&, arr(), k&
- On Error Resume Next
- Set Rg = Application.InputBox("请选择key列", Title:="提示", Type:=8) '返回数值
- t = Rg.Column '取列标
- p = Cells(Rows.count, t).End(xlUp).Row '最后一个单元格行标
- arr1 = ActiveSheet.Cells(1, t).Resize(p).Value
- Set Rg = Application.InputBox("请选择item列", Title:="提示", Type:=8) '返回数值
- u = Rg.Column '取列标
- v = Cells(Rows.count, t).End(xlUp).Row '最后一个单元格行标
- arr2 = ActiveSheet.Cells(1, u).Resize(v).Value
- ReDim krr(1 To UBound(arr1), 1)
- For s = 1 To UBound(arr1)
- krr(s, 0) = arr1(s, 1)
- krr(s, 1) = arr2(s, 1)
- Next
- Set dic = CreateObject("scripting.dictionary")
- For i = 1 To UBound(krr)
- dic(krr(i, 0) & "") = krr(i, 1)
- Next
- Set wg = Application.InputBox("选择被匹配一列", Title:="提示", Type:=8)
- '返回数据一列
- w = wg.Column '取列标
- p = Cells(Rows.count, w).End(xlUp).Row '最后一个单元格行标
- ReDim temp(1 To p, 1)
- temp = Range(Cells(1, w), Cells(p, w))
- ReDim arr(1 To UBound(temp), 1 To 1)
- For k = 1 To UBound(temp)
- arr(k, 1) = dic(temp(k, 1))
- Next
- Set ng = Application.InputBox("返回数据一列", Title:="提示", Type:=8)
- '返回数据一列
- n = ng.Column
- Cells(1, n).Resize(UBound(arr), 1) = arr
- Set dic = Nothing
- Erase arr1
- Erase arr2
- Erase krr
- Erase arr
- Erase temp
- End Sub
复制代码 |
评分
-
1
查看全部评分
-
|