2014-03-27 76 views
0

我有一個excel電子表格(sheet2),記錄數大概在100萬左右。我正在迭代這些記錄,對於每次迭代,我都將一列選定列與另一個大約2000個記錄(位於sheet1中)的範圍進行比較。使用Excel宏在excel範圍內找到一行的最快方法VBA

rangeA = 1 Million rows 'Sheet2 
rangeB = 2000 rows 'Sheet1 

With sheet1 
For Each row In rangeA.Columns.Rows 

    For Each rangeBRow In rangeB.Columns.Rows 
    If (.Cells(rangeBRow.Row,1).Value = CName And .Cells(rangeBRow.Row,2).Value = LBL ...) Then 
    ' Do something cool... set some cell value in sheet2 
    Exit For 
    End If 
    Next rangeBRow 

Next row 
End With 

我上面的代碼的問題是,它是永恆的完成執行。除了爲2000行重複一百萬條記錄之外,還有其他一些最快捷的方法可以在Excel宏中查找一系列行嗎?

謝謝你的時間。

+2

負載萬事成數組,然後比較參考,而不是範圍 – 2014-03-27 11:04:34

+0

大。將嘗試,並回到這裏 –

+1

創建一個字典對象,並使用這兩個標識符作爲關鍵字(連接它們以創建一個複合值)從1M行中加載它。 –

回答

2

12秒檢查5K行鍼對200K:

Sub Compare() 

    Dim rngA As Range, rngB As Range 
    Dim dict As Object, rw As Range 
    Dim a As Application, tmp As String 

    Set a = Application 
    Set dict = CreateObject("scripting.dictionary") 

    Set rngA = Sheet1.Range("A2:F200000") 
    Set rngB = Sheet1.Range("K2:P5000") 

    For Each rw In rngA.Rows 
     'Create a key from the entire row and map to row 
     ' If your rows are not unique you'll have to do a bit more work here 
     ' and use an array for the key value(s) 
     dict.Add Join(a.Transpose(a.Transpose(rw.Value)), Chr(0)), rw.Row 
    Next rw 

    For Each rw In rngB.Rows 
     'does this row match one in range A? 
     tmp = Join(a.Transpose(a.Transpose(rw.Value)), Chr(0)) 
     If dict.exists(tmp) Then 
      rw.Cells(1).Offset(0, -1).Value = dict(tmp) 
     End If 
    Next rw 

End Sub 
+0

回到你身邊,但我想感謝你的幫助!這是救生員。再次感謝。 –

+0

沒問題 - 很高興聽到它爲你工作。 –

+0

比簡單地遍歷rngA.Rows和尋找(使用rng.find)rngB.rows中的每一行要快多少? – wizlog