0
votes
ActiveSheet.PivotTables("PivotTable5").AddDataField ActiveSheet.PivotTables( _
    "PivotTable5").PivotFields(range("hidy!B" & pos).Value), "Sum of " & range("hidy!B" & pos).Value, xlSum

Hello I am ading and removing fields from pivot table according to user drop down control. But in above code I am getting error message "unable to get pivotfields property of the pivottable class". I am very new to VBA excel, please help me figure it out

1

1 Answers

1
votes

Change your code to this:

ActiveSheet.PivotTables("PivotTable5").AddDataField ActiveSheet.PivotTables( _
    "PivotTable5").PivotFields(Sheets("hidy").Range("B" & pos).Value), _
    "Sum of " & Sheets("hidy").Range("B" & pos).Value, xlSum

The problem is you are referencing the value of cell Bpos from Sheet hidy incorrectly.
To further improve your code, try passing the sheets to a variable like this:

Dim ws1 As WorkSheet, ws2 As Worksheet

Set ws1 = Thisworkbook.Sheets("Sheetwithpivot") 'change to your actual sheet
Set ws2 = Thisworkbook.Sheets("hidy") 'sheet with dropdown

ws1.PivotTables("PivotTable5").AddDataField ws1.PivotTables( _
    "PivotTable5").PivotFields(ws2.Range("B" & pos).Value), _
    "Sum of " & ws2.Range("B" & pos).Value, xlSum

This way, you will avoid Runtime errors.