Hey everyone, I need help filtering all pivot tables in a workbook. I have a userform setup with a multi-select listbox and would like to have the page fields (report filter) of all pivot tables auto-filter based on the selections. I was thinking it would be easiest to have the selections copied into a specific column (R) in a "References" worksheet and then use that column as the criteria for filtering the PTs. Here's the code so far which works fine at getting the selections into the appropriate column, but will randomly give me 1004 errors ("Unable to set the Visible property of the PivotItem Class")
I'm stumped as to why I'm getting these errors. There doesn't seem to be any consistency behind them. Also, I realize this is only going to work on PTs in the Data1 worksheet and not all PTs in the workbook. Once this is working I'll move onto applying it to all PTs. Hopefully someone can help me with this as I'm completely stumped. Thanks
Code:
Private Sub CommandButton1_Click()
'Displays selected Regions under Title of Report in a single cell
'Uses selected Regions to filter data
Dim lCount As Long
Dim listitems As String
Dim pt As PivotTable, pi As pivotitem, pf As pivotfield
Dim i As Long
Dim Sheet As Worksheet
Dim wksData As Worksheet
Set wksData = Worksheets("References")
'Displays selected Workspaces into cell Q8 of Report
With ListBox1
For lCount = 0 To .ListCount - 1
If .Selected(lCount) = True Then
listitems = listitems & .list(lCount) & ", "
End If
Next
End With
'Places selected workspaces into a named range for data filtering
Sheets("References").Visible = True
Sheets("References").Select
Range("R1").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.ClearContents
Range("R1").Select
With Me
Counter = 0
For lItem = 0 To .ListBox1.ListCount - 1
If .ListBox1.Selected(lItem) Then
Counter = Counter + 1
Cells(Counter, 18).Value = .ListBox1.list(lItem)
End If
Next lItem
End With
Sheets("Data1").Select
With Me
Set pt = ActiveSheet.PivotTables("PivotTable1")
For Each pi In pt.PivotFields("Region").PivotItems
' if Name is not found in column R, make it invisible.
pi.Visible = Not (wksData.Columns("R").Find(what:=pi.Name, lookat:=xlWhole, LookIn:=xlValues) Is Nothing)[B] 'this line is where the error occurs[/B]
Next
End With
'Places selected workspaces in Report Title
Sheets("Report").Range("Q8") = Left(listitems, Len(listitems) - 2)
Sheets("Report").Select
Range("A1").Select
End
End Sub
I'm stumped as to why I'm getting these errors. There doesn't seem to be any consistency behind them. Also, I realize this is only going to work on PTs in the Data1 worksheet and not all PTs in the workbook. Once this is working I'll move onto applying it to all PTs. Hopefully someone can help me with this as I'm completely stumped. Thanks