-->

VBA code to filter a pivot table based on the valu

2020-05-09 22:43发布

问题:

I’ve searched and tried everything I could find on how to filter a pivot table via VBA code referencing the value of a cell. The table only has one filter and it’s called “name”, this table is part of a score card that I’m putting together and the pivot itself is named “data” the sheet is named “report” and the cell I’m referencing is A5. I’m able to do simple things in VBA and have been using it here and there for a couple of years however this one thing has me pulling my hair out. Could someone please break this down to me in simpleton terms

回答1:

First up, a couple of alternatives to VBA, in case you haven't considered them. If the idea is to get a user to type something into a cell or choose from an in-cell dropdown, then bear in mind that you could perhaps instead add a Slicer and just get the user to click the value they want to filter on in that. Or if you want the user to choose a value from a dropdown, you can 'fake' one using a second PivotTable with only the "name" field in it as a PageField, which looks and acts pretty much like a Data Validation Dropdown. You can then connect that pivot to the main one with a Slicer. See my post at http://dailydoseofexcel.com/archives/2014/08/16/sync-pivots-from-dropdown/

Second, a warning when changing the .visible status via VBA: you want to avoid iterating through PivotItems if you can, because it's slow, as per my extensive article at http://dailydoseofexcel.com/archives/2013/11/14/filtering-pivots-based-on-external-ranges/

Furthermore, when doing anything with PivotItems, you should set the PivotTable.ManualUpdate property to TRUE while the code runs, and then FALSE when you're done, or otherwise the PivotTable tries to refresh each and every time you change the .Visible status of any items.

If you're filtering on just one item, then it's best to either move the field to the Page Fields area and use the .CurrentPage property to instantly filter on that one item. If you don't want it in the Page Fields area, then you can still do this quickly if you have Excel 2010 or later by setting up a 'Master' PivotTable somewhere out of sight, putting the field of interest in the master as a PageField, connecting the Master PivotTable to PivotTable1 ('Slave') with a Slicer, and then changing the .CurrentPage property of the Master, which will then instantly filter the .Slave via the Slicer.

See my answer at VBA to connect slicers (looking for improvements to code) that uses this trick. And see my answer at unable to get the visible property of the pivotitem class for a function that filters a PivotTable on a single PivotItem using the tricks I've outlined above. I'll probably need to post an example of how you use this, but can't right now.