如何在Excel VBA VLOOKUP中将variables用作其中一个值
我在Excel中使用VBA,并将VLOOKUP作为公式分配给单元格。 它工作正常,但我想使用一个variables引用列中包含一个值的最后一个单元格。
在下面的示例中,我将根据封闭文档中元素的数量来更改$ B $ 269的值。
"=VLOOKUP(B2,'Macintosh HD:Users:myself:Documents:[Master_Terms_Users.xlsm]Master_Terms_Users.csv'!$A$1:$B$269,2,FALSE)"
我知道我想用一些东西:
Range("B" & Rows.Count).End(xlUp).Address
有了这个说法,我还没有弄清楚如何把这个结果join到VLOOKUP中。 我知道这些公式返回正确的地址,因为我已经在Debug.Print中使用它。
我试图做这样的事情:
"=VLOOKUP(B2,'Macintosh HD:Users:myself:Documents:[Master_Terms_Users.xlsm]Master_Terms_Users.csv'!$A$1:"&GetLastRowFunct&",2,FALSE)"
但是这没有用。
这是我现在的代码:
Sub GetLastRow() Debug.Print GetLastRowFunct End Sub Function GetLastRowFunct() As String Dim openNwb As Workbook Const MasterPath = "Macintosh HD:Users:myself:Documents:" Dim strNewFileName As String strNewFileName = "Master_Terms_Users.xlsm" Set openNwb = Workbooks.Open(MasterPath & strNewFileName) Dim openNws As Worksheet Set openNws = openNwb.Worksheets(1) GetLastRowFunct = openNws.Range("B" & Rows.Count).End(xlUp).Address openNwb.Close End Function
任何build议,将不胜感激。
我会重写该函数返回整个范围地址,包括工作表,工作簿和path。
Function GetLastRowFunct() As String Const MasterPath = "Macintosh HD:Users:myself:Documents:" Dim openNwb As Workbook, strNewFileName As String strNewFileName = "Master_Terms_Users.xlsm" Set openNwb = Workbooks.Open(MasterPath & strNewFileName) with openNwb.Worksheets(1) GetLastRowFunct = .Range(.cells(1, 1), .cells(rows.count, "B").End(xlUp)).Address(1, 1, external:=true) end with openNwb.Close End Function
公式的构build和分配变得更加简单。
rng.formula = "=VLOOKUP(B2, " & GetLastRowFunct & ", 2, FALSE)"
tbh,我不确定是否需要在Mac上提供自己的方括号。