How to remove a calculated field from a PivotTable using VBA?

To remove a calculated field from a PivotTable using VBA in Excel, you can use the following steps:

   Sub RemoveCalculatedField()
       Dim ws As Worksheet
       Dim pt As PivotTable
       Dim pf As PivotField
       
       ' Set the worksheet that contains the PivotTable
       Set ws = ThisWorkbook.Sheets("Sheet1")
       
       ' Set the PivotTable
       Set pt = ws.PivotTables("PivotTable1")
       
       ' Delete the calculated field
       On Error Resume Next
       Set pf = pt.CalculatedFields("CalculatedFieldName")
       If Not pf Is Nothing Then
           pf.Delete
       Else
           MsgBox "Calculated field not found."
       End If
       On Error GoTo 0
       
   End Sub
  • Open the VBA Editor: Press `ALT` + `F11` to open the Visual Basic for Applications editor.
  • Insert a Module: If you don’t already have a module, insert a new one by right-clicking on “VBAProject (YourWorkbookName)” in the project explorer, selecting “Insert,” and then “Module.”
  • Write the Subroutine: Write a VBA subroutine that targets the specific PivotTable and calculated field you want to remove. Here is a basic example:
  • Adjust the Code:
    • Replace `”Sheet1″` with the name of the worksheet that has your PivotTable.
    • Replace `”PivotTable1″` with the name of your PivotTable. You can usually find this name in the PivotTable Options dialog under the Analyze or Options tab on the Ribbon.
    • Replace `”CalculatedFieldName”` with the name of the calculated field you want to remove.
  • Run the Subroutine: Place the cursor inside the subroutine code and press `F5` to execute the script, or go back to Excel and run the macro from the Developer tab under “Macros”.

This script will find and remove the specified calculated field from the PivotTable. It’s a good idea to handle errors in the case that the field doesn’t exist or if there are other issues. The above script includes basic error handling to show a message box if the calculated field is not found.

Unlock Your Potential

Excel

Basic - Advanced

Access

Access Basic - Advanced

Power BI

Power BI Basic - Advanced

Help us grow the project