如何获取数据透视表中子字段的设置数据点中的最大数字?

问题描述 投票:0回答:2

在下面的截图中,我使用x来获得“一年级”中12.50%的“短片”。但是,我想扩展它以找到“一年级”字段中的最大值并返回名称。例如,在“一年级”中,它将是“高”。

Sub PivotTest()

    Dim pvt As PivotTable: Set pvt = Sheets("Sheet2").PivotTables("PivotTable1")

    x = pvt.GetPivotData("Count Of Height", "Grade", "First Grade", "Height", pvt.PivotFields("First Grade").PivotItems(1)).Value

End Sub

数据透视表截图

enter image description here

excel vba excel-vba pivot-table
2个回答
1
投票

因此,您可以摆弄以下内容,但它为您提供了一个可以使用的形状。为任何打字错误道歉,因为我现在无法粘贴这个。

GetMaxInfo子调用函数MaxHeightInfo,它将Grade作为参数,并返回一个包含高度描述的数组,其中找到了最大计数,例如: “高大”,计数值本身。函数调用后,它们由(0)和(1)索引访问。

函数MaxHeightInfo使用GetPivotData函数检索指定Grade的信息,并将maxCount设置为它找到的最高值。它存储在maxHeight变量中找到此值的高度描述。

Option Explicit

Public Sub GetMaxInfo()

    Msgbox MaxHeightInfo("First Grade")(0)
    Msgbox MaxHeightInfo("First Grade")(1)

    Msgbox MaxHeightInfo("Second Grade")(0)
    Msgbox MaxHeightInfo("Second Grade")(1)

End Sub

Public Function MaxHeightInfo(ByVal myGrade As String) As Variant

    Dim myHeight()
    Dim wb As Workbook
    Dim ws As Worksheet

    Set wb = ThisWorkbook
    Set ws = wb.Worksheets("Sheet2") 'change as appropriate

    Dim pvt As PivotTable

    Set pvt = ws.PivotTables("PivotTable1")

    myHeight = Array("Short","Average","Tall")

    Dim currHeight As Long
    Dim maxCount As Double
    Dim maxHeight As String

    maxCount = 0
    maxHeight = vbNullString

    Dim testVal As Double

    For currHeight = LBound(myHeight) To UBound(myHeight)

        testVal = pvt.GetPivotData("Count of Height"),"Grade", myGrade,"Height", myHeight(currHeight)).Value

        If testVal > maxCount Then
            maxCount = testVal
            maxHeight = myHeight(currHeight)
        End If

    Next currHeight

    MaxHeightInfo = Array(maxHeight, maxCount)
End Function

0
投票

我将通过几个步骤提供非VBA解决方案:首先从enter image description here切换数据透视表的视图

enter image description here

之后,您可以使用max if和索引匹配两个条件来解决它:在示例中:

{=MAX(IF(H3:H8="First Grade";J3:J8))}     

=>此数组公式为您提供一年级的最大高度。然后使用双标准索引匹配,您可以搜索第一年级的最大高度:

{=INDEX(H3:J8;MATCH(1;(H3:H8="First Grade")*(J3:J8=*Cell of the maxIf*);0);2)}  

或整个公式加在一起:

{=INDEX(H3:J8;MATCH(1;(H3:H8="First Grade")*(J3:J8=MAX(IF(H3:H8="First Grade";J3:J8)));0);2)}

在我的Excel上运行得很好。我想人们可以很容易地适应VBA,但不会是最干净的。

© www.soinside.com 2019 - 2024. All rights reserved.