I have one Excel sheet that contains a list of people and their associated departments. In a PivotTable on another sheet, I would like to filter my results so that all items "Assigned To" any of the people in a given department will be displayed.
So far, I have code that will filter the list of people to the desired department, and will create an array that contains the names of all of those people. I have then tried to filter the PivotItems that contain these lists of names to be visible and all others to be hidden, but when I try to run the macro it is just continuously thinking. Is there an easier way to do this?
ActiveSheet.Range("$A$1:$E$175").AutoFilter Field:=4, Criteria1:= _
"DEPARTMENT NAME"
'Selects first visible row of filtered data set & _
create array that contains all filtered names
ActiveSheet.AutoFilter.Range.Offset(1).SpecialCells(xlCellTypeVisible).Cells(3, 2).Select
employeerange = "C" & ActiveCell.Row & ":C" & ActiveSheet.Rows.Count
Dim employeearray As Variant
employeearray = Range(employeerange).Value
'Cycle through all possible items for the given Pivot Field and compare to _
each of the names in the employee array. Set items that match to visible _
and all others to hidden.
Dim PI As PivotItem
Dim element As Variant
With ActiveSheet.PivotTables("PivotTable2").PivotFields("PIVOT FIELD")
For Each PI In .PivotItems
For Each element In employeearray
If PI Like "*" & CStr(element) & "*" Then
PI.Visible = True
Else
PI.Visible = False
End If
Next element
Next PI
End With
Have you checked the first part of your code that builds the array? I can't see your data but I'm not sure that will work the way you hope.
To build up your array, use something like:
As for the 2nd part of the macro..
You're over-testing the match, which if you left it to run would hide everything but the last match.
Use the following instead, which loops through all the .PivotItems but uses a single test to check if the item is in the array.
When iterating over PivotItems, there's a couple of bottlenecks and gotchas that you want to avoid. See my post at http://dailydoseofexcel.com/archives/2013/11/14/filtering-pivots-based-on-external-ranges/ for more on this.
Among other things, you want to set the PivotTable's ManualUpdate property to TRUE while you do the iteration and then back to FALSE when you're done. Otherwise Excel will try to update the PivotTable each time you change the visibility of a PivotItem. And you also want to ensure that at least one item remains visible at all times. I use something like this: