使用数组的vba excel vlookup

我有下面的代码,这是有效的,但有点慢,我想要做同样的,但使用数组

Sub AddValues() Dim Srng As Range Dim search_value As Variant PG = "Data" Ln = 2 Set Srng = Worksheets("Coniguration").Range("_Configuration") LastRow = Worksheets("Data").Range("A1").CurrentRegion.Rows.Count For Ln = 2 To LastRow search_value = Val(ActiveWorkbook.Sheets(PG).Cells(Ln, "A").Value) ActiveWorkbook.Sheets("Data").Cells(Ln, "CA").Value = Application.VLookup(search_value, Srng, 3, False) ActiveWorkbook.Sheets("Data").Cells(Ln, "CB").Value = Application.VLookup(search_value, Srng, 4, False) ActiveWorkbook.Sheets("Data").Cells(Ln, "CC").Value = Application.VLookup(search_value, Srng, 5, False) ActiveWorkbook.Sheets("Data").Cells(Ln, "CD").Value = Application.VLookup(search_value, Srng, 6, False) ActiveWorkbook.Sheets("Data").Cells(Ln, "CF").Value = Application.VLookup(search_value, Srng, 7, False) Next Ln End Sub 

慢的一个确定的来源是你在每次迭代中进行5次相同的search。 您可以改为只查找一次匹配的行,然后复制匹配行中的单元格。 另外有趣的是一次获取工作表参考,并避免在每次迭代中使用Worksheets(name)获取工作Worksheets(name)

 Sub AddValues() Dim Srng As Range, Ln As Long, matchRow, search_value Set Srng = Worksheets("Configuration").Range("_Configuration") With Worksheets("Data") For Ln = 2 To .Cells(.Rows.count, "A").End(xlUp).row search_value = val(.Cells(Ln, "A").Value2) ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' Find matching row only once and copy the results matchRow = Application.match(search_value, Srng.Columns(1), 0) If IsError(matchRow) Then Debug.Print search_value & " : Not found" Else .Cells(Ln, "CA").Resize(, 4).value = Srng.Cells(matchRow, 3).Resize(, 4).Value2 .Cells(Ln, "CF").value = Srng.Cells(matchRow, 7).Value2 End If Next Ln End With End Sub 

这是一个避免循环的方法。 首先在目标单元格中​​input公式,然后将公式转换为值。

 Sub AddValues() Dim Srng As Range Dim LastRow As Long Set Srng = Worksheets("Coniguration").Range("_Configuration") With Worksheets("Data") LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row With .Range("CA2:CA" & LastRow) .FormulaR1C1 = "=VLOOKUP(RC1," & Srng.Address(, , xlR1C1, True) & ", 3, 0)" .Value = .Value End With With .Range("CB2:CB" & LastRow) .FormulaR1C1 = "=VLOOKUP(RC1," & Srng.Address(, , xlR1C1, True) & ", 4, 0)" .Value = .Value End With With .Range("CC2:CC" & LastRow) .FormulaR1C1 = "=VLOOKUP(RC1," & Srng.Address(, , xlR1C1, True) & ", 5, 0)" .Value = .Value End With With .Range("CD2:CD" & LastRow) .FormulaR1C1 = "=VLOOKUP(RC1," & Srng.Address(, , xlR1C1, True) & ", 6, 0)" .Value = .Value End With With .Range("CF2:CF" & LastRow) .FormulaR1C1 = "=VLOOKUP(RC1," & Srng.Address(, , xlR1C1, True) & ", 7, 0)" .Value = .Value End With End With End Sub 

非常感谢ASH和Domenic,这两种方法都比我的代码更好。

最后我会用Domenic提供的那个,因为它是最快的。