我有以下代码来对一系列单元格求和,但我希望它自动填充列,但是当我添加该代码时,它会自动填充总和的结果。我也尝试过使用 .Formula,但我无法让它与 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)
fcell 和 lDate 都被分配为 ActiveCell,但是注释表明 lDate 是 ActiveCell 之前的 1 x Column,所以我做了这个调整,否则你的公式将是循环的并且有问题。
我相信这应该会产生你想要的结果。 它将公式放入选定的单元格中,对从单元格 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(" & rng.Address & ")"
End Sub