Excel – Change the pivot Table filter using VBA

excelexcel-addinsvba

I have a pivot table which contains the "CoB Date" field as shown.
I am trying to create a macro which automatically changes the date as per the user input.
I've written the following macro code. But it shows the error:

Unable to get PivotFields property of the PivotTable class

Can any one help me with this?
Note: Assume that Date Format is not an issue

Code:

Sub My_macro()
    Dim num as String
    num = InputBox(Prompt:="Date", Title:="ENTER DATE")
    Sheets("Sheet1").PivotTables("PivotTable1") _
        .PivotFields("CoB Date").CurrentPage = num
End Sub

enter image description here

Best Answer

As commented the exact same code works on my end.

Sub My_macro()
    Dim num As String
    num = InputBox(Prompt:="Date", Title:="ENTER DATE")
    Sheets("Sheet1").PivotTables("PivotTable1") _
        .PivotFields("CoB Date").CurrentPage = num
End Sub

Suppose you have a data like this:

enter image description here

When you run the macro, it will prompt for a date:

enter image description here

And then after pressing ok, the result would be:

enter image description here

Take note that we assumed that entering of date is not an issue.
So we used a simple data which will eliminate that and so your code works.
The probable issue you're dealing with is if the dates have Time Stamp.
And based on your screen shot, that is the case.

Related Topic