如何用VLOOKUP中的绝对地址替换相对地址?

时间:2015-06-18 06:38:37

标签: excel vba excel-vba vlookup

我已经使用此代码通过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

但我希望我的输出为动态范围的单元格,那么如何使用ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[-2], Sheet17!RC[-8]:R[20]C[-7], 2, FALSE)"函数用绝对地址替换Range()

1 个答案:

答案 0 :(得分:2)

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

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

使用(未)选定/有效范围的任意组合,从主程序中调用此功能。

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

您可以通过最后一个参数选择发电机是否返回" A1"或" $ A $ 1" ...你可以构建它来接受2行布尔值和行单元格等等。

通过使用Ranges,您无需Select / Activate任何内容。