vba vlookup循环增量+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”向下移动一个,但不确定正确的语法在这种情况下不断下移

你的代码没有明确强制ActiveCellWorksheets("Sheet1").Range("B2")但你随后偏离ActiveCell 。 这看起来像是一个将search值赋值的混合方法。 完全避免依靠ActiveCell可能是最好的select。

 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作为VLOOKUPrange_lookup参数返回近似匹配,F2:F5必须按升序sorting。

ActiveCell永远不会改变你的代码。

更换

 search = ActiveCell.Offset(1, 0) 

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