I'm trying to write some code that will return the row, column, and page fields and items after I've highlighted a cell in the values area of the pivot table. For example, if I select a cell that contains a value of $1000, I'd like to the code to pull the row field and item (for example, the field would be Department and item would be Finance), column field and item (for example, the field would be Account and item would be Advertising) and page field and item (for example, the field would be Company and item would be XYZ, Inc.).
This seems like it should be pretty straightforward, because when you hover over any cell in a pivot table, it will show you the drilldown information in the contextures box, however, I'm having a hard time manipulating the pivot table objects because there doesn't seem to be much written on them online or by microsoft.
It seems like the pivotline or pivotlines object might be what I'm looking for, but I can't figure out how to use it.
I originally took this approach and it worked fine until I realized that a rowfields' index is not necessarily it's position in the row field, so I had to scrap this.
Sub ActualDetailDrill()
'after sub is completed, make this sub called when a cell in a pivot table is double-clicked.
Dim NumOfRowItems As Integer
Dim NumOfColItems As Integer
Dim NumOfPageFields As Integer
Dim Field As PivotField
Dim ActualDrillActiveCell As Range
Set ActualDrillActiveCell = Sheets("ActualDrill SQL Build").Range("A1")
NumOfRowItems = ActiveCell.PivotCell.RowItems.Count
i = 1
Do Until i > NumOfRowItems
ActualDrillActiveCell.Value = ActiveCell.PivotTable.RowFields(i).Name
ActualDrillActiveCell.Offset(0, 1).Value = ActiveCell.PivotCell.RowItems(i).Name
ActualDrillActiveCell = ActualDrillActiveCell.Offset(1, 0)
i = i + 1
Loop
End Sub
Any help would be very, very appreciated. This is one of the last steps in a big project I'm working on that will be very helpful to the company I work for.
It's the weekend and I had some time to dig into this interesting question. I think you were pretty close by using
RowItems
andColumnItems
. ThePivotTable.RowFields
are more general though and don't apply at thePivotCell
level.I hate working with Page Fields, but think this is the correct logic for that:
If you aren't already, consider using the VBE's Locals Window. It's great for drilling down (and back up) in the pivot table's object model. That's how I saw that a
ColumnItem
is aPivotItem
whoseParent
is thePivotField
it's in.