vba vlookup循环增量+1

vba vlookup loop increment +1

对于经验丰富的专业人士来说,这应该是一个简单的问题。

1) 我试图在循环的每次迭代中将活动单元格向下偏移一个。

2) 我只能向下移动一位,因为我不确定可用的语法。

3) 我在想 the_result = the_result + 1 但这行不通:(

Sub vlookupTest()

search = Worksheets("Sheet1").Range("B2")

For i = 2 To 5

the_result = Application.WorksheetFunction.vlookup(search, Worksheets("Sheet1").Range("F2:G5"), 2, True)

MsgBox the_result

search = ActiveCell.Offset(1, 0)

Next i


End Sub

我明白为什么循环只向下移动两个单元格并卡住,因为偏移量只从 "B2" 向下移动一个但不确定在这种情况下继续向下移动的正确语法

ActiveCell 在您的代码中永远不会更改。

替换

search = ActiveCell.Offset(1, 0)

ActiveCell.Offset(1, 0).Select
search = ActiveCell

您的代码没有明确强制 ActiveCellWorksheets("Sheet1").Range("B2") 开始,但您随后从 ActiveCell 开始偏移。这似乎是将值赋给 search 的方法的混搭。最好避免完全依赖 ActiveCell

Sub vlookupTest()
    dim searchTerm as variant, the_result as variant

    searchTerm = Worksheets("Sheet1").Range("B2").value
    For i = 2 To 5
        the_result = Application.WorksheetFunction.vlookup(searchTerm , Worksheets("Sheet1").Range("F2:G5"), 2, True)
        MsgBox the_result
        searchTerm = Worksheets("Sheet1").Range("B2").Offset(i - 1, 0).value
    Next i

End Sub

仅供参考,使用 True 作为 range_lookup 参数 VLOOKUP returns 近似匹配和 F2:F5 必须按升序排序。