我正在尝试编写一些代码,这些代码会在我突出显示数据透视表的值区域中的单元格后返回行,列和页面字段和项目。例如,如果我选择一个包含1000美元值的单元格,我想用代码来拉取行字段和项目(例如,字段将是Department,item将是Finance),列字段和项目(例如,该字段将为“帐户”,“项目”为“广告”)和页面字段和项目(例如,该字段为“公司”,“项目”为“XYZ,Inc。”)。
这看起来应该非常简单,因为当您将鼠标悬停在数据透视表中的任何单元格上时,它会在上下文框中显示向下钻取信息,但是,我很难操纵数据透视表对象因为在网上或微软上似乎没有多少写在他们身上。
似乎枢轴线或枢轴线对象可能正是我正在寻找的,但我无法弄清楚如何使用它。
我最初使用这种方法并且它工作正常,直到我意识到行字段的索引不一定是它在行字段中的位置,所以我不得不废弃它。
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
非常非常感谢任何帮助。这是我正在开展的一个大项目的最后一步,这对我工作的公司非常有帮助。
答案 0 :(得分:1)
这是周末,我有时间深入研究这个有趣的问题。我认为您使用RowItems
和ColumnItems
非常接近。 PivotTable.RowFields
更为一般,但不适用于PivotCell
级别。
我讨厌使用Page Fields,但认为这是正确的逻辑:
Sub GetValueFieldStuff()
Dim pvtCell As Excel.PivotCell
Dim pvtTable As Excel.PivotTable
Dim pvtField As Excel.PivotField
Dim pvtItem As Excel.PivotItem
Dim pvtParentItem As Excel.PivotField
Dim i As Long
On Error Resume Next
Set pvtCell = ActiveCell.PivotCell
If Err.Number <> 0 Then
MsgBox "The cursor needs to be in a pivot table"
Exit Sub
End If
On Error GoTo 0
If pvtCell.PivotCellType <> xlPivotCellValue Then
MsgBox "The cursor needs to be in a Value field cell"
Exit Sub
End If
Set pvtTable = pvtCell.PivotTable
For Each pvtField In pvtTable.PageFields
i = 0
For Each pvtItem In pvtField.PivotItems
If pvtItem.Visible Then
i = i + 1
Debug.Print "PageField " & pvtField.Name & " - Pivot Item " & i & " is " & pvtItem.Name
End If
Next pvtItem
Next pvtField
Debug.Print "Value Field Name is " & pvtCell.PivotField.Name
Debug.Print "Value Field Source is " & pvtCell.PivotField.SourceName
For i = 1 To pvtCell.RowItems.Count
Set pvtParentItem = pvtCell.RowItems(i).Parent
Debug.Print "Row Item " & i & " is " & pvtCell.RowItems(i).Name & ". It's parent Row Field is: " & pvtParentItem.Name
Next i
For i = 1 To pvtCell.ColumnItems.Count
Set pvtParentItem = pvtCell.ColumnItems(i).Parent
Debug.Print "Column Item " & i & " is " & pvtCell.ColumnItems(i).Name; ". It's parent Column Field is: " & pvtParentItem.Name
Next i
End Sub
如果您还没有,请考虑使用VBE的本地窗口。它非常适合在数据透视表的对象模型中向下钻取(和备份)。这就是我看到ColumnItem
是PivotItem
的{{1}} Parent
就是PivotField
的方式。