简体   繁体   中英

How to put sum formula in lastrow through vba

Could you tell me how to put sum formula in last row. I don't want to sum of the values in last row. I tried to explain you with below code.

Sub Sum_Formula_In_Lastrow()
lr = Cells(Rows.Count, 2).End(xlUp).Row
lc = Cells(1, 1).End(xlToRight).Column
For x = 4 To lc
Cells(lr, x).Select
Selection.Formula = "=sum(Range(Cells(x, 2), Cells(lr, x)))"
Next x
End Sub

Please suggest me, i know above code is wrong but i'm trying to explain my requirement.

Your variables and range object need to be outside the quotes and concatenated with & . Also the default of Range is .Value . You want to put the Address through not the values.

Sub Sum_Formula_In_Lastrow()
lr = Cells(Rows.Count, 2).End(xlUp).Row
lc = Cells(1, 1).End(xlToRight).Column
For x = 4 To lc
    Cells(lr, x).Formula = "=SUM(" & Range(Cells(2, x), Cells(lr - 1, x)).Address & ")"
Next x
End Sub

Of course this is exactly what R1C1 is designed for. You can fill the whole row without iterating:

Sub Sum_Formula_In_Lastrow()
lr = Cells(Rows.Count, 2).End(xlUp).Row
lc = Cells(1, 1).End(xlToRight).Column
Range(Cells(lr, 4),Cells(lr,lc)).FormulaR1C1 = "=SUM(R2C:R" & lr -1 & "C)" 

End Sub

One last note you want to qualify the ranges to a sheet even if it is the active sheet. Just in case the sheet gets changed.

Sub Sum_Formula_In_Lastrow()
With ActiveSheet
    lr = .Cells(.Rows.Count, 2).End(xlUp).Row
    lc = .Cells(1, 1).End(xlToRight).Column
    .Range(.Cells(lr, 4),.Cells(lr,lc)).FormulaR1C1 = "=SUM(R2C:R" & lr -1 & "C)" 
End With
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM