VBA Code for Subtotal in Excel (3 Ways)

In generic terms, subtotal refers to the total of one set of a larger group of sets. Excel is widely used to store crucial numeric information of students or employees. So, it is often needed to extract a group of subtotal values from a large dataset to understand the actual scenario. Implementing VBA macro is the most effective, quickest and safest method to run any operation in Excel. This article will show you the VBA code for calculating Subtotal in Excel.


VBA Code for Subtotal in Excel: 3 Ways

Consider the following dataset. We have 3 Products named Cricket Ball, Football and Tennis Balland their Sales value in 3 months – January, February and March.

Dataset for VBA Code for Subtotal in Excel

We will calculate the Subtotal for each product for each month in Excel with VBA.


1. Embed VBA Macro to Calculate Subtotal in Excel

This section will show you how to extract the Subtotal for the Cricket Ball, Football and Tennis Ball based on their Sales value in January, February and March in Excel with the VBA code.
The steps to execute this are given below.

Steps:

  • In the beginning, press Alt + F11 on your keyboard or go to the tab Developer -> Visual Basic to open Visual Basic Editor.

  • Next, in the pop-up code window, from the menu bar, click Insert -> Module.

  • Then, 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

Your code is now ready to run.

VBA Code for Subtotal in Excel

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

After the successful code execution, look at the image below to find out the result.

Result of VBA Code for Subtotal in Excel

Finally, our dataset produced the Subtotal of the Sales value for the Cricket Ball, Football and Tennis Ball for the months of January, February and March.

VBA Code Explanation

Sub GenerateSubtotal()

First, provide a name for the sub-procedure of the macro.

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

Then, declare the necessary variables for the macro.

Application.ScreenUpdating = False

Next, turn off the screen updating event.

iValue = 5
xValue = iValue

After that, store the first row from where our data starts in a declared variable. Next, restore the value in another declared variable.

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

Then, sort 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

Later, start 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, turn on the screen updating event.

End Sub

Finally, end the sub-procedure of the macro.


2. Insert VBA Code to Generate Subtotal with Excel Button

In this section, you will learn how to generate the Subtotal for each product in the Excel dataset by clicking a button with the VBA macro. It means, that every time you click on the button, the data from the large spreadsheet will automatically produce the Subtotal for each set of products and display those in a new row of the worksheet.
To execute that, let’s learn how to create a button first in Excel.

Steps to Create a Button to Calculate Subtotal:

  • To assign a button to our dataset, go to the Developer tab.
  • From there, click Insert and select Command Button under the ActiveX Controls group.

Creating Button for VBA Code for Subtotal in Excel

  • There will be a plus symbol (+). Drag and release the symbol to create a button of any size anywhere in your spreadsheet.

The following image represents 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 from there.
    Make sure you keep the Design Mode enabled, otherwise, 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”.
    When you are writing the button name in the Caption box, you will notice that the title on the button is also changing according to the caption.

You can even make further modifications to your button in the Properties window according to your needs.
Once you have put a name on the button, assign a macro code to it.

Steps to Execute VBA Code with the Button to Generate Subtotal:

  • Again, right-click on the button (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. Now, 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.
  • Now, go to the worksheet of interest. 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

You can see the produced result in the above image. The VBA code that we inserted in the button successfully generated the Subtotal of the sales value of Cricket Ball, Football and Tennis Ball for the month of January, February and March.

VBA Code Explanation

Option Explicit

First, forces to declare all the variables explicitly of the file.

Private Sub CommandButton1_Click()
    CalculateSubtotal
End Sub

Then, call the sub-procedure of the macro from the button command.

Sub CalculateSubtotal()

Next, initiate 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, calculate 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

Finally, end the sub-procedure of the macro.

Read More: How to Insert Subtotals in Excel


3. VBA to Populate Subtotal for a Specific Range of Data with Button

The above code produced Subtotal for every set of products there were. But suppose you want to calculate the Subtotal only for a specific set of products. This section will show you how to get that by clicking Excel Button with the VBA code.

Steps:

  • You already learned how to create a button, modify it and assign a macro to it in the previous section. Once you have done all that, now it’s time to write the code according to the requirements for this section.
  • Now, 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.
  • Now, before clicking the button you must select the range first that you want to calculate the Subtotal.

Select Range for VBA Code for Subtotal in Excel

  • For instance, we will generate the Subtotal of the sales value only for the set of Cricket Ball and Football, so we drag through only the products of Cricket Ball and Football and leave Tennis Ball out of the selection.
  • Then, click the button.

Result of VBA Code for Selected Subtotal in Excel

As a result, Subtotals of the sales value only for the set of Cricket Ball and Football are produced, not for the Tennis Ball.

VBA Code Explanation

Option Explicit

First, forces to declare all the variables explicitly of the file.

Private Sub CommandButton1_Click()
    GenerateSubtotal
End Sub

Then, call the sub-procedure of the macro from the button command.

Sub GenerateSubtotal()

Next, initiate 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, calculate 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

Finally, end the sub-procedure of the macro.


Download Workbook

You can download the free practice Excel workbook from here.


Conclusion

This article showed you 3 demonstrations of the VBA code for calculating Subtotal in Excel. I hope this article has been very beneficial to you. Feel free to ask if you have any questions regarding the topic.


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