I am trying to copy the data values of a pivot table into another worksheet, but because I do filtering in the pivot table which "hides" a few of the row labels, when I loop through the pivot items of the pivot field in the row label, it loops a few more times than it actually should. To illustrate my problem here is the code I use.
Sub Prob()
Dim Ptable1 as PivotTable
Dim PField as PivotField
Dim PField2 as PivotField
Dim NumOfPItem as Long
Dim PItem as PivotItem
Dim aCell as Range
Set Ptable1 = ActiveSheet.PivotTables("PivotTable1")
With Ptable1.PivotFields("DataCol5")
.CurrentPage = "12/2/2018"
End With
PField = Ptable1.PivotFields("DataCol1")
NumOfPItem = PField.PivotItems.Count
For each PItem in PField.PivotItems
'Some code to get a cell reference in another worksheet
'and then some code to copy the value from the pivot table to cells.
aCell.Offset(0,1).Value = PField2.PivotItems("XX01").DataRange.Cells(PItem.Position,1)
Next PItem
End Sub
I just prepared something simple so that it would capture the main problem I am facing.
Unfiltered pivot table:
Field arrangements:
This is the pivot table after filtering it.
I tried looping through pivot items that were visible using the PivotItems.Visible
property but the items are all visible hence looping through every pivot item there is. Leading to my next screenshot.
As seen, all items are selected so when looping through all "visible" pivot items from the pivot field, it would loop through it 5 times because there is 5 different items. However, in this example, after I do some filtering I end up with just 1 row label, so it should only be looping once for what is present in the pivot table. What am I doing wrong here?