繁体   English   中英

如何通过VBA将求和公式放在lastrow中

[英]How to put sum formula in lastrow through vba

你能告诉我如何将求和公式放在最后一行。 我不想对最后一行的值求和。 我试图用下面的代码向您解释。

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

请建议我,我知道上面的代码是错误的,但是我正在尝试解释我的要求。

您的变量和范围对象必须在引号之外,并与&串联。 同样,Range的默认值是.Value 您要通过地址而不是值。

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

当然,这正是R1C1设计的目的。 您可以填充整个行而无需迭代:

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

最后一个要使范围限定为工作表的便笺,即使它是活动工作表也是如此。 以防万一工作表被更改。

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.

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