1

我是 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 上

4

1 回答 1

5

要将放在活动单元中,请使用循环尝试:

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

要在没有循环的情况下在活动单元中放置一个,请尝试:

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

要将公式放置在没有循环的活动单元格中,请尝试:

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
于 2013-09-14T12:00:15.537 回答