How to edit a calculated field in a PivotTable using VBA?

To edit a calculated field in a PivotTable using VBA, you’ll need to manipulate the `PivotTable` object and use the `CalculatedFields` collection to modify the existing calculated field. Here’s a general guide on how to do it:

  • Find the PivotTable: First, identify the worksheet and PivotTable you want to modify.
  • Access the Calculated Field: Use the `CalculatedFields` property of the `PivotTable` object to access the calculated field you want to edit.
  • Modify the Formula: Change the formula of the calculated field.

Here’s a sample VBA code that demonstrates how to perform these steps:

Sub EditCalculatedField()
    Dim ws As Worksheet
    Dim pt As PivotTable
    Dim calcField As PivotField
    Dim calculatedFieldName As String
    Dim newFormula As String
    
    ' Define the worksheet and PivotTable name
    Set ws = ThisWorkbook.Sheets("Sheet1") ' Adjust to your sheet name
    Set pt = ws.PivotTables("PivotTable1") ' Adjust to your PivotTable name
    
    ' Define the name of the calculated field and the new formula
    calculatedFieldName = "MyCalculatedField" ' Adjust to your calculated field name
    newFormula = "=SUM(Sales) - SUM(Costs)" ' Adjust to your desired formula
    
    ' Attempt to access the calculated field
    On Error Resume Next
    Set calcField = pt.CalculatedFields(calculatedFieldName)
    On Error GoTo 0
    
    ' Check if the calculated field was found
    If Not calcField Is Nothing Then
        ' Edit the calculated field's formula
        calcField.Formula = newFormula
        MsgBox "Calculated field '" & calculatedFieldName & "' has been updated.", vbInformation
    Else
        MsgBox "Calculated field '" & calculatedFieldName & "' not found.", vbExclamation
    End If
End Sub

Explanation:

  • Worksheets and PivotTables Identification: You need to specify the worksheet and PivotTable you are working with, using their respective names.
  • CalculatedFields: This is a collection within the PivotTable object that stores all calculated fields. You access an existing calculated field by referencing its name.
  • Setting Formula: Once you have a reference to the calculated field, you can modify its `.Formula` property to update the formula.
  • Error Handling: The `On Error Resume Next` and subsequent checking if `calcField` is `Nothing` is a simple way to handle situations where the calculated field name might not exist, thus avoiding runtime errors.

Adjust the sheet name, PivotTable name, calculated field name, and formula as needed for your specific use case.

Unlock Your Potential

Excel

Basic - Advanced

Access

Access Basic - Advanced

Power BI

Power BI Basic - Advanced

Help us grow the project