VBA to Check for and Remove/Add Calculated Pivot Field

cwpyrant

New Member
Joined
Jul 27, 2017
Messages
9
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
 

Excel Facts

Spell Check in Excel
Press F7 to start spell check in Excel. Be careful, by default, Excel does not check Capitalized Werds (whoops)

Forum statistics

Threads
1,224,823
Messages
6,181,185
Members
453,020
Latest member
Mohamed Magdi Tawfiq Emam

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top