I am trying to write a VBA script to update a pivot table's filters based on the value in two cells but I keep getting a 1004 run-time error. I have tried various approaches based on answers to other questions but I still can't figure out what the problem is.
Note: I have read that the error sometimes occurs because pivot tables require at least one visible value, but this error occurs even if I set Visible = True
VBA Code:
Private Sub PageItemFilter()
Dim pvtF As PivotField
Dim pvtI As PivotItem
Dim startDate As Date
Dim endDate As Date
Dim filterDate As Date
startDate = Range("start_date").Value
endDate = Range("end_date").Value
Set pvtF = Worksheets("selection").PivotTables("PivotTable1").PivotFields("[tbl_Main].[TransactionDate].[TransactionDate]")
pvtF.ClearAllFilters
For Each pvtI In pvtF.PivotItems
filterDate = DateValue(Mid(pvtI.Name, 24, 10))
If filterDate >= startDate And filterDate <= endDate Then
Debug.Print (pvtI.Name)
Debug.Print (TypeName(pvtI))
Debug.Print (pvtI.Visible)
pvtI.Visible = True
Else
pvtI.Visible = False
End If
Next pvtI
End Sub
Output (first item):
[tbl_Main].[TransactionDate].&[2019-08-05T00:00:00]
PivotItem
True
Error: Run-time error '1004': Application-defined or object-defined error
pvtI.Visiblebut I can't set it. If there is another approach to this problem, even if it isn't a VBA solution, I'd be happy to try it - E PpvtI.Visible = False. I've picked up that the code only loops through the items that are already visible (if I don't clear all filters) and I wonder if that isn't a clue to what the problem is? - E P