2012-03-21 77 views
6

當我選擇了一個包含數值的範圍後,我想通過VBA在每列的底部輸入一個=SUM公式,即在最後一個選定行之後的行上。對於每個列,它應該將整個選擇的相應列中的所有值相加。如何使用VBA合計選定範圍的列?

我該怎麼做?

現在,我使用宏記錄器給出的代碼:ActiveCell.FormulaR1C1 = "=SUM(R[-10]C:R[-1]C)"。問題是當我的範圍超過10行時,它不會考慮底部10以上的行。

enter image description here

回答

6

這工作:

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 

例子:

enter image description here

1

你也可以做這樣的事情沒有VBA:

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

這將對公式所在單元格之上的所有單元格進行求和。

8

這是一個簡單的非VBA方法。

選擇您想要求和的單元格並按Alt - =

快照

enter image description here

這裏是單行VBA代碼,做同樣的事情。

Sub AutoSum() 
    '~~> After you select your range 
    Application.CommandBars.ExecuteMso ("AutoSum") 
End Sub