N
nc
I have two macros below, to one to create and the other to delete calculated
field.
When I run create, the macro completes successfully. When I run the latter
I get an error message "Method 'Delete' of object 'PivotField' failed. Can
you please help me amend the 'DeleteCalcFields_Click() macro.
Private Sub DeleteCalcFields_Click()
For Each fld In _
Worksheets("Create calc
fields").PivotTables("PivotTable1").CalculatedFields
fld.Delete
Next
End Sub
Private Sub CreateCalcFields_Click()
Dim rngItems As Range
Dim ws As Worksheet
Dim pt As PivotTable
Dim c As Range
Dim pf As PivotField
Set ws = Worksheets("Create calc fields")
Set pt = ws.PivotTables("PivotTable1")
Set rngItems = ws.Range("AddItems")
For Each c In rngItems
On Error Resume Next
Set pf = ws.PivotTables("PivotTable1").CalculatedFields(c.Value)
On Error GoTo 0
If Not pf Is Nothing Then
ws.PivotTables("PivotTable1").CalculatedFields(c.Value) _
.StandardFormula = c.Offset(0, 1).Value
Else
ws.PivotTables("PivotTable1").CalculatedFields.Add _
c.Value, c.Offset(0, 1).Value, True
' pt.PivotFields(c.Value).Orientation = xlDataField
End If
Next c
End Sub
field.
When I run create, the macro completes successfully. When I run the latter
I get an error message "Method 'Delete' of object 'PivotField' failed. Can
you please help me amend the 'DeleteCalcFields_Click() macro.
Private Sub DeleteCalcFields_Click()
For Each fld In _
Worksheets("Create calc
fields").PivotTables("PivotTable1").CalculatedFields
fld.Delete
Next
End Sub
Private Sub CreateCalcFields_Click()
Dim rngItems As Range
Dim ws As Worksheet
Dim pt As PivotTable
Dim c As Range
Dim pf As PivotField
Set ws = Worksheets("Create calc fields")
Set pt = ws.PivotTables("PivotTable1")
Set rngItems = ws.Range("AddItems")
For Each c In rngItems
On Error Resume Next
Set pf = ws.PivotTables("PivotTable1").CalculatedFields(c.Value)
On Error GoTo 0
If Not pf Is Nothing Then
ws.PivotTables("PivotTable1").CalculatedFields(c.Value) _
.StandardFormula = c.Offset(0, 1).Value
Else
ws.PivotTables("PivotTable1").CalculatedFields.Add _
c.Value, c.Offset(0, 1).Value, True
' pt.PivotFields(c.Value).Orientation = xlDataField
End If
Next c
End Sub