如何使用VBA将Excel公式放入一个dynamic范围的单元格中?

我是VBA新手,正在使用以下代码片段来使用vlookup函数填充一系列单元格:

With wbk1.Sheets("classes") .Range("AA2:AA" & .Range("C" & .Rows.Count).End(xlUp).Row).Formula = "=VLOOKUP(C2,lookup!$A$2:$B$14,2,FALSE)" 'Actual vlookup 

为了使这个dynamic,我想用dynamic引用replace.Range("AA2:AA" & .Range("C" & .Rows.Count)部分(在我的情况下,在同一张工作表中的第一个空列)。

首先,我find了这个单行的第一个空列:

 first_empty_column = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column 

但是,当我这样做

 With wbk1.Sheets("classes") .Range(ws.Cells(1, first_empty_column) & .Range("C" & .Rows.Count).End(xlUp).Row).Formula = "=VLOOKUP(C2,lookup!$A$2:$B$14,2,FALSE)" 'Actual vlookup 

我得到“运行时错误'1004':应用程序定义的一个对象定义的错误。

在这种情况下dynamic定义硬编码范围的语法是什么?

您需要使用以下Range reference逻辑:

 'PSEUDO-CODE .Range(LeftTopCell, RightBottomCell) 

LeftTopCellRightBottomCell都可以用任何有效的范围参考来设置。 而且,您不能将参考结合到两张不同的纸张的范围内。 您在单个范围参考中引用了wsSheets("classes")

试试这个:

 With wbk1.Sheets("classes") .Range(.Cells(1, first_empty_column), _ .Cells(.Range("C" & .Rows.Count).End(xlUp).Row, first_empty_column)).Formula = "=VLOOKUP(C2,lookup!$A$2:$B$14,2,FALSE)" 'Actual vlookup End With