Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum columns for a selected range using VBA?

Tags:

excel

vba

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

like image 214
user1204868 Avatar asked Mar 21 '12 08:03

user1204868


3 Answers

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
like image 161
Siddharth Rout Avatar answered Sep 28 '22 02:09

Siddharth Rout


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

like image 43
Jean-François Corbett Avatar answered Sep 28 '22 01:09

Jean-François Corbett


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.

like image 40
markblandford Avatar answered Sep 28 '22 01:09

markblandford