答案 0 :(得分:1)
使用数据透视表字段(PivotFields
)的这个关键是要检查几个条件以确保您正在处理所需的字段。在您的情况下,您希望确保查看Rows
并且位于第一个位置(顶级)的字段。
我有一整套公共数据透视表函数,可以公开这些类型的检查,以方便我。我正在使用其中两个来向您展示问题的解决方案。
Option Explicit
Public Function TopLevelRows() As Long
Dim thisWS As Worksheet
Dim thisPT As PivotTable
Set thisWS = ThisWorkbook.Sheets("Sheet1")
Set thisPT = thisWS.PivotTables(1)
Dim numberOfTopLevelRows As Long
numberOfTopLevelRows = 0
Dim pField As PivotField
For Each pField In thisPT.PivotFields
If PivotFieldIsRow(thisPT, pField.Name) And _
(PivotFieldPosition(thisPT, pField.Name) = 1) Then
'--- there will only be one of these, so iterate on the items
Dim pItem As PivotItem
'--- we can't assume that the .Count equals the number of
' items because there may be a "(blank)" entry
'Debug.Print "count = " & pField.PivotItems.count
For Each pItem In pField.PivotItems
If pItem.Caption <> "(blank)" Then
numberOfTopLevelRows = numberOfTopLevelRows + 1
End If
Next pItem
End If
Next pField
Debug.Print "there are " & numberOfTopLevelRows & " top level rows in the pivot table"
TopLevelRows = numberOfTopLevelRows 'return value
End Function
Private Function PivotFieldIsRow(ByRef pTable As PivotTable, _
ByVal ptFieldName As String) As Boolean
Dim field As PivotField
PivotFieldIsRow = False
For Each field In pTable.RowFields
If field.Name = ptFieldName Then
PivotFieldIsRow = True
Exit Function
End If
Next field
End Function
Private Function PivotFieldPosition(ByRef pTable As PivotTable, _
ByVal ptFieldName As String) As Long
Dim field As PivotField
PivotFieldPosition = 0
For Each field In pTable.PivotFields
If field.Name = ptFieldName Then
If TypeName(field.position) = "Error" Then
'--- we'll get an error if the field is not included as a
' row or column. this isn't a problem, but there's no
' real position in this case, so return 0
Else
PivotFieldPosition = field.position
End If
Exit Function
End If
Next field
End Function
现在在单元格A30中写下公式=TopLevelRows()
,你应该得到你的结果。
答案 1 :(得分:0)