How to change the PivotTable data field aggregation using VBA?

To change the PivotTable data field aggregation using VBA, follow the steps below. The procedure involves accessing the specific data field of the PivotTable and setting its `Function` property to the desired aggregation method. Common aggregation functions include `xlSum`, `xlCount`, `xlAverage`, `xlMax`, `xlMin`, among others.

Here’s a basic example of how to achieve this:

Sub ChangePivotTableDataFieldAggregation()

    Dim ws As Worksheet
    Dim pt As PivotTable
    Dim pf As PivotField
    Dim dataFieldName As String
    
    ' Set the worksheet and PivotTable
    Set ws = ThisWorkbook.Sheets("Sheet1") ' Change to your sheet name
    Set pt = ws.PivotTables("PivotTable1") ' Change to your PivotTable name
    
    ' Specify the data field you want to change
    dataFieldName = "Sales" ' Change to your data field name
    
    ' Set the PivotField
    On Error Resume Next
    Set pf = pt.PivotFields(dataFieldName)
    On Error GoTo 0
    
    If Not pf Is Nothing Then
        ' Change the aggregation function
        pf.Function = xlSum ' Change to your desired aggregation (e.g., xlSum, xlCount, xlAverage)
    Else
        MsgBox "Data field not found!", vbExclamation
    End If

End Sub
  • Open the VBA Editor: Press `ALT + F11` in Excel to open the VBA editor.
  • Insert a Module: Go to `Insert > Module` to create a new module.
  • Write the VBA code:
  • Customize the Code:
    • Replace `”Sheet1″` with the name of your worksheet containing the PivotTable.
    • Replace `”PivotTable1″` with the actual name of your PivotTable.
    • Replace `”Sales”` with the name of the data field you wish to change.
    • Modify `xlSum` to any other aggregation function as needed (e.g., `xlCount`, `xlAverage`, `xlMax`, `xlMin`).
  • Run the Macro: Press `F5` or run the macro from the Excel interface to see the changes apply to your PivotTable.

Remember, you need to have a PivotTable already set up with the specified data field in order to change its aggregation function using this VBA code. Also, ensure that macros are enabled in Excel to allow the VBA code to execute.

Unlock Your Potential

Excel

Basic - Advanced

Access

Access Basic - Advanced

Power BI

Power BI Basic - Advanced

Help us grow the project