如何用绝对地址在VLOOKUP中replace相对地址?

我已经使用此代码通过VBA应用VLOOKUP。

Sub lookup() Sheets("Sheet16").Select Cells(1, 10).Select ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[-2], Sheet17!RC[-8]:R[20]C[-7], 2, FALSE)" Selection.AutoFill Destination:=Range(Cells(1, 10), Cells(10, 10)), Type:=xlFillDefault End Sub 

但我希望我的输出为一个dynamic范围的单元格,所以我怎样才能替代ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[-2], Sheet17!RC[-8]:R[20]C[-7], 2, FALSE)"与绝对地址使用Range()函数?

=VLOOKUP(...)公式的生成放在接受范围的函数中作为参数,并返回公式string,例如

 Function GenLookupFormula(Arg As Range, LTab As Range, ColPar As Integer, _ Optional AdrAbsolute As Boolean = True) As String GenLookupFormula = "=VLOOKUP(" & Arg.Address(AdrAbsolute, AdrAbsolute) & "," & _ LTab.Address(AdrAbsolute, AdrAbsolute) & "," & _ ColPar & ",FALSE)" End Function 

从主程序中调用这个函数,不pipe是否有select/有效范围的组合。

 Sub TestGenLookup() ' Sheet1 active, cell A1 selected/active, relative addressing Selection.Formula = GenLookupFormula([A1], [A3:B5], 1, False) ' cell B1 in active sheet, absolute addressing - omit parameter ' result still in active sheet, VLOOKUP arguments in other sheets [B1].Formula = GenLookupFormula(Sheets(2).[A1], Sheets(3).[B3:C12], 2) ' any cell in any other (not active) sheet - absolute addressing using parameter ' mix & mingle ... all is possible Sheets(3).Range("D1").Formula = GenLookupFormula(Sheets(2).[A1], Sheets(1).[B3:C12], 2, True) End Sub 

您可以通过最后一个参数来select是否生成器返回“A1”或“$ A $ 1”…你可以build立这个接受2布尔行$和col $单独等等等。

通过使用范围,你不需要Select / Activate任何东西。