你能告诉我如何将总和公式放在最后一行。我不想总结最后一行的值。我试着用下面的代码解释你。
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
请建议我,我知道上面的代码是错误的,但我想解释我的要求。
答案 0 :(得分:1)
您的变量和范围对象必须在引号之外并与&
连接。此外,范围的默认值为.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