在VBA中查找多列数据的速度比VLookup更快?

时间:2014-05-29 19:39:04

标签: excel vba excel-vba vlookup worksheet-function

我有一个大型数据处理电子表格,用于查找组件编号,然后将相关列加载到数组中。目前我正在使用VLookup函数,这是一个在循环中使用数千次的非常慢的函数。

我目前的代码部分:

Set drng = Sheets(Data).Range("D2:AS" & imax)

On Error Resume Next 
For i = 1 To 7 

    jmax = Sheets(ShtName(i)).UsedRange.Rows.Count
    For j = 3 To jmax

        Component= Sheets(ShtName(i)).Cells(j, 1).Value2

        DataVar(1) = Application.VLookup(Component, drng, 32, False) 
        DataVar(2) = Application.VLookup(Component, drng, 35, False) 
        DataVar(3) = Application.VLookup(Component, drng, 42, False) 
        DataVar(4) = Application.VLookup(Component, drng, 11, False) 
        DataVar(5) = Application.VLookup(Component, drng, 15, False) 
        DataVar(6) = Application.VLookup(Component, drng, 24, False) 
        DataVar(7) = Application.VLookup(Component, drng, 18, False) 
        DataVar(8) = Application.VLookup(Component, drng, 38, False) 
        DataVar(9) = Application.VLookup(Component, drng, 21, False) 
        DataVar(10) = Application.VLookup(Component, drng, 29, False)

     Next j
Next i
On Error GoTo 0

有更快的方法吗?

1 个答案:

答案 0 :(得分:2)

由于您需要来自同一行的多列信息,并且您知道哪些列具有该信息,您所要做的就是找到数据所在的行,然后您可以直接引用这些单元格。您可以使用匹配功能来确定行。

请参阅此代码:

For i = 1 To 7 

    jmax = Sheets(ShtName(i)).UsedRange.Rows.Count
    For j = 3 To jmax 

        Component = Sheets(ShtName(i)).Cells(j, 1).Value2

        With Sheets(Quarter)
            ComponentRow = WorksheetFunction.Match(Component, .Range("D:D"), 0)
            DataVar(1) = .Cells(ComponentRow, 35).Value2 
            DataVar(2) = .Cells(ComponentRow, 38).Value2 
            DataVar(3) = .Cells(ComponentRow, 45).Value2 
            DataVar(4) = .Cells(ComponentRow, 14).Value2 
            DataVar(5) = .Cells(ComponentRow, 18).Value2 
            DataVar(6) = .Cells(ComponentRow, 27).Value2 
            DataVar(7) = .Cells(ComponentRow, 21).Value2 
            DataVar(8) = .Cells(ComponentRow, 41).Value2 
            DataVar(9) = .Cells(ComponentRow, 24).Value2 
            DataVar(10) = .Cells(ComponentRow, 32).Value2 
        End With

    Next j

Next i