为什么 ListObject 使用绝对单元格引用自动填充公式而不是循环代码?

问题描述 投票:0回答:1

我有一个命名表(ListObject),我正在尝试使用循环函数用公式填充该表。在我的表格中,D 列中有一个价格,“E:P”列中有空白单元格,代表一年中的月份。这些列用于用户输入。

我希望“Q:AB”列中填充每个月的价格产品和产品数量,以给出每月的总成本,如果用户更改“E:”列中的任何值,则可以更改此值。 P”。例如,“Q2”的输出 vba 公式应为“$D2*E2”。然后它会计算包含价格的每一行(通常是十行,每行都有不同的价格)。

我不知道为什么,但我的输出单元格(“Q2:AB10”)都完全相同:“$D$2*$E$2”

我尝试使用范围而不是 cell.addresses 但是(可能是因为我试图循环的变量?)我不断收到错误 1004。此代码运行,但即使在循环时它似乎也没有改变输出通过。我正在使用的具体代码如下所示:

With Worksheets (i) 'this is defined farther up in the sub
  lrow2 = .Range("A" & Rows.Count).End(xlUp).row 'find last row
  col = Range("D" & lrow2).Column 'find correct column

'Confirm cells' address reference correct cells
  Debug.Print (Cells(lrow2 + 1, 4).Address)
  Debug.Print (Cells(lrow2 + 1, col + 1).Address)
  Debug.Print (Cells(lrow2 + 1, col + 13).Address)

For c = col  To col + 12
  Cells(lrow2 + 1, c + 13).Formula = "=" & Cells(lrow2 + 1, 4).Address & "*" & Cells(lrow2 + 1, c + 1).Address
Next c

我需要动态代码以接受额外的行(一次 10 行),但列将保持不变,我只是经验不足,不知道解决此问题的最佳方法。

excel vba loops excel-formula array-formulas
1个回答
0
投票

要了解有关

Range.Address
属性的更多信息,请参阅此链接:

范围.地址属性

修改:

Cells(lrow2 + 1, c + 13).Formula = "=" & Cells(lrow2 + 1, 4).Address & "*" & Cells(lrow2 + 1, c + 1).Address

与:

.Cells(lrow2 + 1, c + 13).Formula = "=" & .Cells(lrow2 + 1, 4).Address(False, True, xlA1) & "*" & .Cells(lrow2 + 1, c + 1).Address(False, False, xlA1)
© www.soinside.com 2019 - 2024. All rights reserved.