6

After I have selected a range containing numerical values, I want to, via VBA, input a =SUM formula at the bottom of each column, i.e. on the row after the last selected row. For each column it should sum all of the values in the corresponding column of the entire selection.

How can I do this?

Right now, I am using the code given by the macro recorder: ActiveCell.FormulaR1C1 = "=SUM(R[-10]C:R[-1]C)". The problem is when my range gets bigger than 10 rows it will not take the rows above the bottom 10 into consideration.

enter image description here

4 Answers 4

8

Here is a simple non-VBA Approach.

Select the cells where you want the sum and press Alt-=.

SNAPSHOT

enter image description here

And here is a one-line VBA code that does the same thing.

Sub AutoSum()
    '~~> After you select your range
    Application.CommandBars.ExecuteMso ("AutoSum")
End Sub
Sign up to request clarification or add additional context in comments.

Comments

6

This works:

Sub MakeSums()
    Dim source As Range
    Dim iCol As Long
    Dim nCol As Long
    Dim nRow As Long

    Set source = Selection

    nCol = source.Columns.Count
    nRow = source.Rows.Count
    For iCol = 1 To nCol
        With source.Columns(iCol).Rows(nRow).Offset(1, 0)
            .FormulaR1C1 = "=SUM(R[-" & nRow & "]C:R[-1]C)"
            .Font.Bold = True
        End With
    Next iCol

End Sub

Example:

enter image description here

Comments

1

You could also do something like this without VBA:

=SUM(OFFSET(INDIRECT(CELL("address")),1-ROW(),0,ROW()-1,1))

This will sum all cells above the cell in which the formula exists.

Comments

1

Here is a quick trick to sum selected cells in vba code.

Private Sub Sum_Click()
    MsgBox Application.Sum(Range(Selection.Address))
End Sub

This is what I was searching for when I landed on this thread so maybe it will help someone.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.