Thursday, October 6, 2011

SUBTOTAL -- my first VBA program

'Calculate subtotal of numeric columns below the cell selected

Option Explicit

Sub subtotal()

Dim result, data As Range
Dim lastrow As Long

If TypeName(Selection) <> "Range" Then Exit Sub

Set result = Selection

lastrow = ActiveSheet.UsedRange.Rows.Count
Set data = Range(Selection.Offset(2, 0), Cells(lastrow, result.Column))
result.Formula = "=SUBTOTAL(9," & data.Address(external:=True) & ")"
End Sub

No comments: