VBA Code for Subtotal in Excel (3 Ways)

Consider the following dataset. We have 3 Products named Cricket Ball, Football, and Tennis Ball, and their Sales value across 3 months, January, February, and March. We will calculate the Subtotal for each product for each month.

Dataset for VBA Code for Subtotal in Excel


Method 1 – Embed VBA Macro to Calculate Subtotals in Excel

Steps:

  • Press Alt + F11 on your keyboard or go to the Developer tab and select Visual Basic to open the Visual Basic Editor.

  • In the pop-up code window, click Insert and select Module.

  • Copy the following code and paste it into the code window.
Sub GenerateSubtotal()
Dim iColumn As Integer
Dim iValue As Integer
Dim xValue As Integer
Application.ScreenUpdating = False
iValue = 5
xValue = iValue
Range("C5").CurrentRegion.Offset(1).Sort Range("C6"), 1
Do While Range("C" & iValue) <> ""
    If Range("C" & iValue) <> Range("C" & (iValue + 1)) Then
    Rows(iValue + 1).Insert
    Range("C" & (iValue + 1)) = "Subtotal " & Range("C" & iValue).Value
    For iColumn = 6 To 8 'Columns to Calculate Sum
    Cells(iValue + 1, iColumn).Formula = "=SUM(R" & xValue & "C:R" & iValue & "C)"
    Next iColumn
    Range(Cells(iValue + 1, 1), Cells(iValue + 1, 8)).Font.Bold = True
    iValue = iValue + 2
    xValue = iValue
    Else
    iValue = iValue + 1
    End If
    Loop
Application.ScreenUpdating = True
End Sub

VBA Code for Subtotal in Excel

  • Press F5 on your keyboard or select Run then Run Sub/UserForm. You can also just click on the small Run icon in the sub-menu bar to run the macro.

  • Here’s the result.

Result of VBA Code for Subtotal in Excel

VBA Code Explanation

Sub GenerateSubtotal()

Provides a name for the sub-procedure of the macro.

Dim iColumn As Integer
Dim iValue As Integer
Dim xValue As Integer

Declares the necessary variables for the macro.

Application.ScreenUpdating = False

Turns off the screen updating event.

iValue = 5
xValue = iValue

Stores the first row from where our data starts in a declared variable and restores the value in another declared variable.

Range("C5").CurrentRegion.Offset(1).Sort Range("C6"), 1

Sorts the data so that each set of data is grouped together.

Do While Range("C" & iValue) <> ""
    If Range("C" & iValue) <> Range("C" & (iValue + 1)) Then
    Rows(iValue + 1).Insert
    Range("C" & (iValue + 1)) = "Subtotal " & Range("C" & iValue).Value
    For iColumn = 6 To 8 'Columns to Calculate Sum
    Cells(iValue + 1, iColumn).Formula = "=SUM(R" & xValue & "C:R" & iValue & "C)"
    Next iColumn
    Range(Cells(iValue + 1, 1), Cells(iValue + 1, 8)).Font.Bold = True
    iValue = iValue + 2
    xValue = iValue
    Else
    iValue = iValue + 1
    End If
    Loop

Starts looping through Column C to find matched values. It continues iterating until there is no match. When it doesn’t find any match, it throws the Sum value.

Application.ScreenUpdating = True

After that, turns on the screen updating event.

End Sub

End the sub-procedure of the macro.


Method 2 – Insert VBA Code to Generate a Subtotal with a Button

Create a Button to Calculate Subtotal:

  • Go to the Developer tab.
  • Click Insert and select Command Button under the ActiveX Controls group.

Creating Button for VBA Code for Subtotal in Excel

  • The cursor changes to a plus symbol (+). Drag and release the symbol to create a button of any size anywhere in your spreadsheet.

  • Here’s what our button looks like.

  • To modify the caption of the button, right-click on the button. A list of options will appear. Select Properties.
    Make sure you keep the Design Mode enabled, or you won’t be able to change the button’s appearance.

  • A Properties window will come up. Write any name that you want to give your button in the Caption In our case, we named our button Click to Subtotal.

Execute VBA Code with the Button to Generate Subtotals:

  • Right-click on the button (and make sure the Design Mode is turned on) and select View Code from the option list. You can also double-click the button to go to the code window.

Assigning Macro in Button for VBA Code for Subtotal in Excel

  • You will be redirected to the code window. Copy the following code and paste it there.
Option Explicit
Private Sub CommandButton1_Click()
    CalculateSubtotal
End Sub
Sub CalculateSubtotal()
    Worksheets("Subtotal Button").Activate
    Range("C4:H" & Cells(Rows.Count, "H").End(xlUp).Row).Subtotal GroupBy:=1, Function:=xlSum, TotalList:=Array(4, 5, 6), Replace:=True, PageBreaks:=False
End Sub

VBA Code inside Button for Subtotal in Excel

  • Save this macro code.
  • Go to the worksheet.
  • Click the button. Don’t forget to disable the Design Mode this time.

  • After you click the button, you will see that the dataset now consists of the Subtotal sales value of each set of products.

Result of VBA Code with Button for Subtotal in Excel

VBA Code Explanation

Option Explicit

Forces to declare all the variables explicitly of the file.

Private Sub CommandButton1_Click()
    CalculateSubtotal
End Sub

Calls the sub-procedure of the macro from the button command.

Sub CalculateSubtotal()

Initiates the sub-procedure of the macro.

Worksheets("Subtotal Button").Activate
Range("C4:H" & Cells(Rows.Count, "H").End(xlUp).Row).Subtotal GroupBy:=1, Function:=xlSum, TotalList:=Array(4, 5, 6), Replace:=True, PageBreaks:=False

This piece of code first activates the worksheet of interest (“Subtotal Button” is our worksheet name). Then, it calculates the Subtotal of the Array value of the 4th, 5th and 6th fields of the range C4:H from the dataset with the Range.Subtotal method.

End Sub

Ends the sub-procedure of the macro.

Read More: How to Insert Subtotals in Excel


Method 3 – VBA to Populate the Subtotal for a Specific Range of Data with a Button

Steps:

  • Create a button, modify it, and assign a macro to it as in the previous section.
  • Copy the following code and paste it into the code window of the button.
Option Explicit
Private Sub CommandButton1_Click()
    GenerateSubtotal
End Sub
Sub GenerateSubtotal()
    Worksheets("Subtotal Selected").Activate
    Selection.Subtotal GroupBy:=1, Function:=xlSum, TotalList:=Array(4, 5, 6), Replace:=True, PageBreaks:=False
End Sub

VBA Code for Selected Subtotal in Excel

  • Save this macro code and go to the worksheet of interest.
  • Select the range you want to subtotal.
  • Click on the button.

Select Range for VBA Code for Subtotal in Excel

  • We will generate the Subtotal of the sales value only for Cricket Ball and Football, so we dragged through those products for the selection and clicked the button.

Result of VBA Code for Selected Subtotal in Excel

VBA Code Explanation

Option Explicit

Forces to declare all the variables explicitly of the file.

Private Sub CommandButton1_Click()
    GenerateSubtotal
End Sub

Call the sub-procedure of the macro from the button command.

Sub GenerateSubtotal()

Initiates the sub-procedure of the macro.

Worksheets("Subtotal Selected").Activate
    Selection.Subtotal GroupBy:=1, Function:=xlSum, TotalList:=Array(4, 5, 6), Replace:=True, PageBreaks:=False

This piece of code first activates the worksheet of interest (“Subtotal Selected” is our worksheet name). Then, it calculates the Subtotal of the Array value of the 4th, 5th, and 6th fields of the selected range from the dataset with the Selection.Subtotal property.

End Sub

Ends the sub-procedure of the macro.


Download the Workbook


Related Articles

<< Go Back To Subtotal in Excel | Learn Excel

Get FREE Advanced Excel Exercises with Solutions!
Sanjida Ahmed
Sanjida Ahmed

Sanjida Ahmed, who graduated from Daffodil International University with a degree in Software Engineering, has worked with SOFTEKO since 2021. She has written over 100 articles on Excel & VBA and, since 2022, has worked as the Project Manager of the Excel Extension Development Project in the Software Development Department. Since starting this software development, she has established an outstanding workflow encompassing a full SDLC. She always tries to create a bridge between her skills and interests in... Read Full Bio

2 Comments
  1. Hello, I have some issues with the part Cells(iValue + 1, iColumn).Formula = “=SUM(R” & xValue & “C:R” & iValue & “C)”

    The column where changes happen is G, while the subtotal sum should happen in column Q.
    I’m unable to get it done. What does the R, the C:R and the C stand for? Are these the columns? I do not see any R column in the given example…

    • Hello, LOCHIA!
      Thanks for sharing your problem with us!
      Actually, in the following formula, C stands for Column, and R stands for Row. The While loop block of codes is searching Column C in a loop for values that match. Up until there is no match, iteration continues. If no match is found, it tosses the Sum value.

      ="=SUM(R" & xValue & "C:R" & iValue & "C)"

      Can you please send me your excel file via email? ([email protected]).
      So that, I can solve your problem.

      Good Luck!

      Regards,
      Sabrina Ayon
      Author, ExcelDemy.

Leave a reply

Advanced Excel Exercises with Solutions PDF

 

 

ExcelDemy
Logo