Hi all, I have the code below where I am trying to first check if a specific calculated field (sField, derived from a button name) already exist in the pivot and then if it does, remove it, if it doesn't, then add it. Parts of the code works but Im currently stuck on the IF where I am checking if the field exist in the table. I've tried many variations, the one below was one last ditch effort. I suspect that there is confusion happening between what the field is called before entering the table (sField) and then which I am naming sField " Calc" on this line: pt.AddDataField pt.PivotFields(sField), sField + " Calc", xlSum . But maybe Im way off base, any help would be great!
VBA Code:
Sub Toggle_PercentCalc_Field()
Dim pt As PivotTable
Dim pf As PivotField
Dim sField As String
Dim shp As Shape
Set pt = ActiveSheet.PivotTables(1)
Set shp = ActiveSheet.Shapes(Application.Caller)
sField = shp.TextFrame.Characters.Text
Dim pi As PivotItem
If pt.DataFields(sField).Parent.PivotItems(.Name) = Visible Then
For Each pf In pt.DataFields
If pf.SourceName = "TC %" Then Exit For
Next
pf.DataRange.Cells(1, 1).PivotItem.Visible = False
shp.Fill.ForeColor.Brightness = 0.5
Else
pt.AddDataField pt.PivotFields(sField), sField + " Calc", xlSum
pt.PivotFields(sField + " Calc").NumberFormat = "0.0%"
shp.Fill.ForeColor.Brightness = 0
End If
End Sub