[英]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
. 同样,Range的默认值是
.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. 当然,这正是R1C1设计的目的。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.