提问人:FionaP 提问时间:8/19/2023 最后编辑:braXFionaP 更新时间:8/21/2023 访问量:56
有没有办法自动填充 WorksheetFunction.Sum 下列?
Is there a way to autofill WorksheetFunction.Sum down the column?
问:
我有以下代码对一系列单元格求和,但我希望它自动填充列,但是当我添加该代码时,它会自动填充求和的结果。我也尝试使用.公式,但我无法让它与 Dims 一起使用,但我想这会让我使用自动填充。每次运行宏时,Dims 都会有所不同,行数也会有所不同。
Dim fCell As Range
Dim fDate As Range
Dim lDate As Range
Dim rng As Range
Set fcell = ActiveCell 'this is J2
Set fDate = Range("C2")
Set lDate = ActiveCell ' this is I2
Set rng = Range([fDate], [lDate])
fCell.Select
fCell = WorksheetFunction.Sum(rng)
答:
0赞
Cade
8/20/2023
#1
fcell 和 lDate 都被分配了 ActiveCell,但注释表明 lDate 在 ActiveCell 之前是 1 x 列,所以我进行了此调整,否则您的公式将是循环的并且有问题。
我相信这应该会产生你所追求的。 它将一个公式放在选定的单元格中,以求和从单元格 C2 到所选单元格左侧列的所有内容。
Public Sub ApplyFormula()
Dim fCell As Range
Dim fDate As Range
Dim lDate As Range
Dim rng As Range
Set fCell = ActiveCell ' Current Cell Selected
Set fDate = Range("C2")
Set lDate = ActiveCell.Offset(ColumnOffset:=-1) ' this is 1 x Column before the Active Cell
Set rng = Range(fDate, lDate)
fCell.Formula = "=SUM(" & REPLACE(rng.Address, "$", "") & ")"
End Sub
评论
0赞
FionaP
8/20/2023
嗨,是的,我已经能够自己做到这一点,但我的问题是我想自动填充列,但公式使用绝对引用。因此,自动填充始终使用 fDate 和 lDate。我需要 C2:I2 类型引用,但我不知道如何将其更改为它。有什么想法吗?
0赞
Cade
8/20/2023
如果您希望公式排除 $,则可以将其包装在替换中。即 fCell.Formula = “=SUM(” & REPLACE(rng.地址, “&”, “”) & “)”
0赞
FionaP
8/20/2023
对不起,伙计,我不明白,这并没有将其更改为相对引用
0赞
FionaP
8/20/2023
啊,你打字了,当你的意思是$时 - 我现在已经整理好了。谢谢 x
0赞
Cade
8/21/2023
很抱歉,我还更新了原始答案以反映此更改
评论