Search code examples
excelvbaworksheet-function

Is there a way to autofill WorksheetFunction.Sum down the column?


I have the following code to Sum a range of cells, but I want it to autofill down the column, but when I add that code it autfills the result of the sum. I also tried using .Formula, but I couldn't get it to work with the Dims, but I imagine that would let me use autofill. the Dims will be different each time the Macro is run and the number of rows will be different too.

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)

Solution

  • Both fcell and lDate are being assigned ActiveCell, but the comment indicates that lDate is 1 x Column before the ActiveCell so I have made this adjustment, otherwise your formula would be circular and have an issue.

    I believe this should produce what you are after. It puts a formula in the selected Cell to SUM everything from cell C2 until the column to the left of the selected cell.

    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