Home » excel » excel – Runtime Error 1004: Unable to get the PivotTables property of the Worksheet class

excel – Runtime Error 1004: Unable to get the PivotTables property of the Worksheet class

Posted by: admin April 23, 2020 Leave a comment

Questions:

I recorded this macro to update the date range of 16 charts. But, as you can see I am getting a Run-time error.

I have looked at other threads on stackoverflow that relate to this but none come close. The darn help button on excel doesn’t help either. Can you please advise? Here is the code:

ActiveSheet.ChartObjects("Chart 18").Activate
ActiveChart.Axes(xlCategory).Select
ActiveSheet.ChartObjects("Chart 18").Activate
With ActiveSheet.PivotTables("PivotTable2").PivotFields("Date")
    .PivotItems("Sep-15").Visible = False
    .PivotItems("Aug-14").Visible = True
End With
How to&Answers:

Here’s some simple code that should get you close. You will need to change “MySheet” in this code to the name of the sheet containing the pivot table in your workbook, and your Date field must truly be text formatted in the “Mmm-YY” format.

Sub ShowThirteenDatesStartingLastMonth()
    Sheets("MySheet").PivotTables("PivotTable2").PivotCache.Refresh

    Dim Dt As String

    With Sheets("MySheet").PivotTables("PivotTable2").PivotFields("Date")        
    For h = 1 To .PivotItems.Count - 1
        On Error Resume Next
        .PivotItems(h).Visible = False
    Next h

    For i = 1 To 13
        On Error Resume Next
        Dt = Format(DateSerial(Year(Date), Month(Date) - i, 1), "Mmm-YY")
        .PivotItems(Dt).Visible = True
    Next i
    End With
End Sub

Answer:

It’s hard to know without an example of your workbook, but I would try naming the sheet rather than using “activesheet”. It’s also typically a bad idea to activate or select anything, and instead you should allow the code to do as much work as it can without selecting anything.
Something like this might work better:

With Sheets("MySheet").PivotTables("PivotTable2").PivotFields("Date")
.PivotItems("Sep-15").Visible = False
.PivotItems("Aug-14").Visible = True
End With

Answer:

As Josh said, you should reference the exact sheet name and maybe even the exact Pivot table name.

Also, you should avoid using .Select and instead declare a variable for each pivot chart, for example.