How to calculate running totals in a PivotTable using VBA?

Calculating running totals in a PivotTable using VBA involves using the PivotTable object model to set the appropriate options. Here’s a step-by-step guide to achieve this through VBA:

Step 1: Create a PivotTable

Before you can calculate running totals, you need to ensure the PivotTable is already created. Normally, you can record a macro while creating one to understand the VBA code necessary to create a PivotTable.

Step 2: Set Up VBA Code for Running Totals

Assuming you have an existing PivotTable, you can adjust the data field settings to display running totals. Here is a basic VBA script to configure a running total:

Sub AddRunningTotalToPivotTable()
    Dim ws As Worksheet
    Dim pt As PivotTable
    Dim pf As PivotField
    Dim dataFieldName As String
    Dim baseFieldName As String

    ' Define your worksheet and PivotTable names
    Set ws = ThisWorkbook.Sheets("Sheet1") ' Change to your sheet name
    Set pt = ws.PivotTables("PivotTable1") ' Change to your PivotTable name

    ' Define the data field and base field names
    dataFieldName = "Sales" ' Change to your data field name
    baseFieldName = "Month" ' Change to your base field name

    ' Access the data field you want to change
    With pt.PivotFields(dataFieldName)
        ' Set calculation to running total
        .Calculation = xlRunningTotal
        ' Set the base field for the running total
        .BaseField = baseFieldName
    End With

    MsgBox "Running total set for " & dataFieldName & " based on " & baseFieldName
End Sub

Key Points:

  • Worksheet and PivotTable References:
    • Adjust the `ws` and `pt` variables to point to the correct worksheet and PivotTable in your workbook.
  • Data Field and Base Field:
    • `dataFieldName` is the field you want to calculate the running total for (usually a numeric field).
    • `baseFieldName` is the field used as the base for calculation, typically a time-based field like “Month” or “Date”.
  • Running Total Calculation:
    • The `.Calculation` property is set to `xlRunningTotal` to enable the running total.
    • The `.BaseField` specifies the field over which the running total is calculated.
  • Error Handling:
    • You might want to include error handling to ensure that your specified fields and tables exist.

This VBA script will modify an existing PivotTable to display a running total for a specified data field based on a base field like time or another category. Adjust the worksheet, PivotTable, and field names as per your dataset.

Unlock Your Potential

Excel

Basic - Advanced

Access

Access Basic - Advanced

Power BI

Power BI Basic - Advanced

Help us grow the project