VBA计算从活动单元到其上述单元值的总和

时间:2013-09-14 06:24:03

标签: vba excel-vba excel

我是VBA Noob并寻求帮助,我的ActiveCell目前在单元格A8中,我想使用循环获得单元格A7到A1的总和,然后该值将出现在单元格A8中。同样,如果我将我的ActiveCell更改为C8,我仍然会得到相同的程序。

记录宏给了我这个

Range("A1:A7,A8").Select
Range("A8").Activate
ActiveCell.FormulaR1C1 = "=SUM(R[-7]C:R[-1]C)"

我想将其更改为循环,以便A1:A7的值出现在我的ActiveCell A8上

1 个答案:

答案 0 :(得分:4)

要将置于activecell中,使用循环,请尝试:

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

要在没有循环的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

要将公式放置在activecell 没有循环,请尝试:

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