如何使用VBA将excel公式放入动态范围的单元格中?

时间:2017-12-04 07:45:04

标签: excel vba excel-vba

我是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

为了使这个动态化,我想用动态引用替换.Range("AA2:AA" & .Range("C" & .Rows.Count)部分(在我的例子中是同一工作表中的第一个空列)。

首先,我找到第一个带有这种单线的空列:

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':应用程序定义了一个对象定义的错误。

在此上下文中动态定义硬编码范围的语法是什么?

1 个答案:

答案 0 :(得分:1)

您需要使用以下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
相关问题