简体   繁体   中英

Update a pivot table's sourcedata based on sheet filter

After filtering on a column I end up with 4 rows instead of 105 but my code is still seeing 105 rows, how can i automatically refresh my pivot table as i appy a filter.I'll filter my sheet many times so i want my pivot table to adapt to my filtering (don't want to apply the filter directly on the pivot table but to automatize the procedure)

筛选项目

LastRow = alarmes.Cells(Rows.Count, 1).End(xlUp).Row
LastCol = 11
Set PRange = alarmes.Cells(1, 1).Resize(LastRow, LastCol)

Set PCache = Application.ThisWorkbook.PivotCaches.Create _
    (SourceType:=xlDatabase, SourceData:=PRange)
Set PTable = PCache.CreatePivotTable _
    (TableDestination:=graphe_dos.Cells(1, 1), TableName:="Test")

You can't create a PivotTable from a non-contiguous range. And filtering a PivotTable's source data has no effect on a PivotTable. So you either need to delete the hidden rows in the source Table, and then use the entire remaining Table block, or filter the PivotItems in the PivotTable itself.

If you want to filter a PivotField to match the items in the Table, then you need to iterate through the PivotItems (or SlicerItems if there is a Slicer connected to the PivotField) and set the .Visible (or .Selected for SlicerItems) property to TRUE for the things you want to keep, and FALSE for other items.

There are many potential bottlenecks when doing this, and if you don't code around them, then it might take minutes to iterate through a PivotField with as little as 20,000 PivotItems in it. See my post at http://dailydoseofexcel.com/archives/2013/11/14/filtering-pivots-based-on-external-ranges/ for more on what to watch out for, and then see my answers at the following links that program around these bottlenecks:

Filtering on SlicerItems

Filtering on PivotItems

Perhaps an easy workaround is to set up a PivotTable Slicer, and use the value that the user selects in that PivotTable Slicer to filter the Table on the same value. See How to link a Table and a Pivot Table using Slicers in Excel?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM