顶级数据透视表的计数功能

时间:2018-03-12 13:44:23

标签: excel excel-formula pivot-table

我有一个如下所示的数据透视表:

enter image description here

我想编写一个函数来计算数据透视表中最高级别的条目数(即A,B,C和D)。我可以编写哪些Excel函数会为此数据透视表产生4的结果?

谢谢!

2 个答案:

答案 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)

只需将第二个字段完全拖出数据透视表,从“值”区域的行区域拖动第一个字段,如果是文本字段,您将自动获得字段数的COUNT。 (否则,将聚合从SUM更改为COUNT)

enter image description here