【问题标题】:How to put an excel formula to a dynamic range of cells using VBA?如何使用 VBA 将 excel 公式放入动态范围的单元格中?
【发布时间】:2017-12-04 07:45:03
【问题描述】:

我是 VBA 新手,正在使用以下 sn-p 使用 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’:应用程序定义的对象定义的错误。

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

【问题讨论】:

    标签: vba excel


    【解决方案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
    

    【讨论】:

    • 像魅力一样工作 - 非常感谢 - 您能否在答案的第 3 行详细说明“,_”的用法?
    • underscore 只是将长行代码分成两行。我在这里使用它来提高代码的可读性
    • 其实是space后跟underscore
    猜你喜欢
    • 1970-01-01
    • 2012-08-17
    • 2022-12-03
    • 2022-01-14
    • 2015-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多