使用VBA在动态范围内使用VLOOKUP

时间:2013-08-27 18:46:28

标签: excel vba excel-vba

我正在尝试设置VB,因此我可以对动态范围的值执行VLOOKUP。它总是从同一个地方开始,但它可能会根据H4中的任何值而进一步下降。

编辑:这是代码,它的工作原理。

谢谢Alex!

Public Sub State()

    Dim refRng As Range, ref As Range, dataRng As Range
    Dim i As Variant
    Dim count As Integer
    i = Sheet2.Range("H1").Value
    i = i + 3 'offset of when to start

    Set refRng = Sheet2.Range("D8:" & Cells(8, i).Address) '//horizontal range of look up values
    Set dataRng = Sheet13.Range("A:C") '//data block you want to look up value in

    For Each ref In refRng
    ref.Offset(1, 0) = Application.WorksheetFunction.VLookup(refRng, dataRng, 2, True)
    Next ref
End Sub

1 个答案:

答案 0 :(得分:0)

这可能有所帮助:

Sub LookUp()
    Dim refRng As Range, ref As Range, dataRng As Range

    Set refRng = Worksheets(1).Range("D8:F8") //horizontal range of look up values
    Set dataRng = Worksheets(2).Range("A1:B4") //data block you want to look up value in

    For Each ref In refRng
        ref.Offset(1, 0) = WorksheetFunction.VLookup(ref, dataRng, 2, 0)
    Next ref
End Sub

在此设置对查找值和要查询的数据的引用。然后迭代水平范围内的值并查找值。