VBA 计算从活动单元格到其以上单元格值的总和
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18798996/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VBA calculate sum from active cell to its above cell values
提问by mobinuya
I am VBA Noob and seeking for help, my ActiveCell is currently in cell A8 and I want to get the sum of cell A7 to A1 with the use of loop then the value will appear in cell A8. Also, same with if I change my ActiveCell to C8 and I will still get same procedure.
我是 VBA Noob 正在寻求帮助,我的 ActiveCell 目前在单元格 A8 中,我想使用循环将单元格 A7 与 A1 的总和然后该值将出现在单元格 A8 中。另外,如果我将 ActiveCell 更改为 C8,我仍然会得到相同的程序。
Record macro gave me this one
录制宏给了我这个
Range("A1:A7,A8").Select
Range("A8").Activate
ActiveCell.FormulaR1C1 = "=SUM(R[-7]C:R[-1]C)"
I want to change it to loop so that the value of A1:A7 will appear on my ActiveCell A8
我想把它改成循环,这样 A1:A7 的值就会出现在我的 ActiveCell A8 上
回答by Gary's Student
To place the valuein the activecell, using a looptry:
要将值放置在活动单元格中,请使用循环尝试:
Sub SumAboveLoop()
Dim r As Range, rAbove As Range
Dim v As Variant
Set r = ActiveCell
Set rAbove = Range(r.Offset(-1, 0), Cells(1, r.Column))
v = 0
For Each rr In rAbove
v = v + rr.Value
Next rr
r.Value = v
End Sub
To place a valuein the activecell without a loop, try:
要在没有循环的情况下在 activecell 中放置一个值,请尝试:
Sub SumAboveV()
Dim r As Range, rAbove As Range
Dim wf As WorksheetFunction
Set wf = Application.WorksheetFunction
Set r = ActiveCell
Set rAbove = Range(r.Offset(-1, 0), Cells(1, r.Column))
r.Value = wf.Sum(rAbove)
End Sub
To place a formulain the activecell without a loop, try:
要在没有循环的情况下在活动单元格中放置公式,请尝试:
Sub SumAboveF()
Dim r As Range, rAbove As Range
Dim wf As WorksheetFunction
Set wf = Application.WorksheetFunction
Set r = ActiveCell
Set rAbove = Range(r.Offset(-1, 0), Cells(1, r.Column))
r.Formula = "=SUM(" & rAbove.Address & ")"
End Sub