2017-07-14 173 views
0

我有2個工作表,第一個有40k +(Sheet1S)條目,我必須在第二個工作表(Sheet2S)中查找,它有300k條目。VBA Vlookup with Scripting Dictionary

我已經編寫了這個腳本來運行基於腳本dictonary的vlookup,如果我將for循環調整爲10行(我取消註釋了實際的for循環),它將起作用。

Sub aTest() 
    Dim a As Variant, i As Long 
    With CreateObject("Scripting.Dictionary") 
     a = Sheets("Sheet2S").Range("A1").CurrentRegion.Value 
     For i = 2 To 10 
     'For i = 2 To UBound(a, 1) 
     .Item(a(i, 1)) = Application.Index(a, i, 0) 
    Next 

    a = Sheets("Sheet1S").Range("A1").CurrentRegion.Value 
    'For i = 2 To UBound(a, 1) 
    For i = 2 To 10 
     If .exists(a(i, 1)) Then 
      a(i, 2) = .Item(a(i, 1))(2) 
      'a(i, 4) = .Item(a(i, 2))(3) 
     Else 
      a(i, 2) = "#N/A" 
     End If 
    Next i 
    End With 
    Sheets("Sheet1S").Range("a1").CurrentRegion.Value = a 
End Sub 

現在根據一個古老的線程(How to optimize vlookup for high search count ? (alternatives to VLOOKUP))字典方法應該只有幾秒鐘:不過,如果我使用所有的行它需要年齡。如果我使用Application.Vlookup,則需要10分鐘才能完成對我來說太長的完全相同的工作表。我正在使用Excel 2016,並添加了Microsoft腳本運行時。難道我做錯了什麼?

在此先感謝。

最佳

+0

你實現這個方法看似尋常給我。多少列?你在這兩個列表中有沒有重複的地方? –

+0

兩張表都包含15列,可能有重複。然而,隨着保羅比卡的實施,它就像一個魅力。 – Uwewewe

回答

0

我測試你的實現,而不指數(),並限制在2列:把2.2秒:

Option Explicit 

'Use Early Binding: VBA Editor -> Tools -> References -> Add Microsoft Scripting Runtime 

Public Sub VLookUpTest() 
    Const N = "#,###" 
    Dim a As Variant, i As Long, d As Dictionary 
    Dim lr1 As Long, lr2 As Long, t As Double, tt As String 

    t = Timer 
    Set d = New Dictionary 
    With d 

     a = Sheets("Sheet2S").Range("A1").CurrentRegion.Columns("A:B").Formula 
     lr2 = UBound(a) 
     For i = 2 To lr2 
      .Item(a(i, 1)) = a(i, 2) 
     Next 

     a = Sheets("Sheet1S").Range("A1").CurrentRegion.Columns("A:B").Formula 
     lr1 = UBound(a) 
     For i = 2 To lr1 
      a(i, 2) = IIf(.exists(a(i, 1)), .Item(a(i, 1)), "#N/A") 
     Next i 
     Sheets("Sheet1S").Range("a1").CurrentRegion.Columns("A:B").Formula = a 

    End With 

tt = Format(Timer - t, "#,###.00") & " seconds" 
Debug.Print "S1 rows: " & Format(lr1, N) & "; S2 rows: " & Format(lr2, N) & "; Time: " & tt 

    'S1 rows: 50,001; S2 rows: 350,001; Time: 2.23 seconds 

End Sub 
+1

哇,這太神奇了!非常感謝。爲了好玩,我已經在Sheet1和Sheet2上用300000x15進行了測試,考慮到表單的大小,它仍然非常快。 'S1行:306 271; S2行:306 271;時間:267,23秒 – Uwewewe