How to Use the Subtotal Function in Excel and VBA
Contents
Defining a Range
In Microsoft Excel, a “range" of cells is a continuous group of cells across rows and columns. Here’s some valid examples of ranges with references to the cells:
Any single cell like H54, C3.
A part of any row Eg: D4:G4, H10:N10.
A part of any column Eg: D4:D9, H10:H20.
A combination of rows and columns/a table of any size Eg: A2:D20, G5:J15.
The Range Function
In VBA we can refer to a range using the range function.
Syntax
Range(“<expression>")
Where <expression>
is the columns and rows/cells that should be part of a range.
For Example:
Range(“D4:G4") – marked in yellow in the image below.
Range(“A6:D20") – marked in green in the image below.
Range(“G5:K19") – marked in blue in the image below.
Actions on Range
The following are some actions that can be performed on a range:
 Select a range
 Delete a range
 Clear contents of a range
 Apply some formula on a range of numeric values
Subtotal Formula
You might have worked with mathematical formulas in cells like sum, average, count, standard deviation, etc… These are straightforward functions that do a calculation on the specified range of cells depending on whether the cells are visible/hidden (that is, if filters are applied).
Syntax:
Subtotal(<function number>
, <range ref>
)
Where function number indicates a corresponding calculation function to be performed (see the table below) and <range ref> refers to the range of cells to be considered for the calculation.
List of function numbers:
Function num  Function num  Function 
All hidden values are included  All hidden values are ignored  
1  101  AVERAGE 
2  102  COUNT 
3  103  COUNTA 
4  104  MAX 
5  105  MIN 
6  106  PRODUCT 
7  107  STDEV 
8  108  STDEVP 
9  109  SUM 
10  110  VAR 
11  111  VARP 
Check out the difference between sum formula and subtotal formula:
Cell B12 uses a sum formula:
Now both display the total of cells (B2 to B10). 162 is the value displayed in both the cells.
When a filter is applied on the “Price" column, we can see the subtotal formula considers only the filtered cells for calculation.
Range.Subtotal Function Using VBA
The subtotal formula used in cells can be used in VBA code too, using two methods.
Syntax 1:
Range(<expression>
)=Subtotal (GroupBy, Function, TotalList, [Replace], [PageBreaks], [SummaryBelowData]
)
Each of the parameters is explained in the table below:
Name  Parameter is Required / Optional  Data type of Parameter  Description 
GroupBy  Required  Long  This is the field to group by, as a onebased integer offset. 
Function  Required  XlConsolidationFunction  This is the subtotal function. 
TotalList  Required  Variant  This is an array of onebased field offsets, indicating the fields to which the subtotals are added. 
Replace  Optional  Variant  True value is used to replace existing subtotals. It is the default value. 
PageBreaks  Optional  Variant  True to add page breaks after each group. The default value is False. 
SummaryBelowData  Optional  XlSummaryRow  Places the summary data relative to the subtotal. 
Worksheets("Mydemo").Activate Selection.Subtotal GroupBy:=1, Function:=xlSum, TotalList:=Array(2, 3)
The program activates the specified sheet and calculates the sum of the selected cells or range that are filtered and visible.
Don’t worry if this Range.Subtotal method is confusing or not clear. We have a better method to use the same Subtotal function in VBA.
Syntax 2
Range(<cell reference>
) = Application.WorksheetFunction.Subtotal(<function number>
, Range(<range referenc
e>))
Where:

<cell reference>
is the cell number in which the return value of this function is to be displayed. 
<function number>
is the number that decides what calculation needs to be done. The available values are explained in the “List of function numbers” table above. 
<range reference>
is the range of cells that have to be considered for the calculation.
Examples
Display the Sum as a Subtotal in Another Cell
Let us do the same calculation which we did in the previous example.
Sub st_demo() ' declare necessary variable Dim subt ' calculate and store the subtotal value in a variable subt = Application.WorksheetFunction.Subtotal(9, Range("B2:B10")) 'display the variable value in the cell Range("B13") = subt End Sub
The output is calculated and displayed in the cell B13. It can also be displayed in a message box if required.
Since this is achieved through VBA code, in this image above, the formula is not visible in the ’formula bar’ as in the previous examples.
Program to Display the Cheapest Food Item on a Menu
Sub st_demo() ' declare necessary variable Dim subt ' find the cheapest of the displayed menu items. subt = Application.WorksheetFunction.Subtotal(5, Range("B2:B10")) 'display the variable value in the cell MsgBox subt &amp; " Rupees is the minimum about required to purchase some food item from this store. " End Sub
Please note that the function number used in this program is “5" which stands for “Min" value.
Now, I’ll run the same program after removing the singledigit values using a filter:
Conclusion
The subtotal formula/function can be useful especially when several rows/columns are hidden because of filters.
Pros of this method:
 Using a subtotal function in VBA can be useful when the value keeps changing during the runtime of lengthy code and this value deviates the flow of the program.
Cons of this method:
 There is no “undo" option when you manipulate data with VBA code.
 The formula is not visible. Because of this, the user may not know what or why a particular value is displayed.
 As this is not achieved through an Excel formula that autocalculates values, the value will remain the same in the cell until your code is rerun after every new filter option.