VBA Excel 从主元中获取最大值 table

VBA Excel get max value from pivot table

我正在尝试获取数据透视表中的最大值 table 并显示相应的行。

例如

行标签 |资源总和

第 1 行:22

第 2 行:30

行 3" 15

它将显示第 2 行,因为 30 是最大值。

我有的就在这里

Function getMaxPT()
Dim pt As PivotTable
Dim max As Integer
Dim PTfield As PivotField

Set pt = Worksheets("Sheet").PivotTables("PivotTable1")

For Each PTfield In pt.RowFields
    Debug.Print PTfield.Name
Next PTfield
End Function

PS。我在 windows 7

上使用 excel 2010

要获取特定字段的值,您应该遍历其单元格。然后进行一些比较以取最大值。这个 returns 数据透视表中所有 RowFields 的最大值:

Function getMaxPT()

    Dim pt As PivotTable
    Dim max As Double
    Dim PTfield As PivotField
    Dim var As Variant

    Set pt = Worksheets(1).PivotTables("PivotTable1")

    For Each PTfield In pt.RowFields
        For Each var In PTfield.DataRange.Cells
            If max < var Then max = var
            Debug.Print var
        Next var
    Next PTfield

    MsgBox max

End Function

如果只对一列感兴趣(假设关闭小计和单列行字段),您可以避免循环并引用列的数据范围

Public Sub test()
    Dim localMax As Long, myRange As Range, found As Range
    Dim pvt As PivotTable
    Set pvt = Worksheets("Sheet").PivotTables("PivotTable1")
    Set myRange = pvt.PivotFields("Sum of Resource").DataRange
    localMax = Application.WorksheetFunction.Max(myRange)
    Set found = myRange.Find(localMax)
    Debug.Print localMax, Worksheets("Sheet").Cells(found.Row, pvt.RowRange.Column)
End Sub

数据:


结果:

局部最大值=19; b(行 = 5)


对于所有列,而不仅仅是一列,如果关闭小计和总计,请使用

Set myRange = Worksheets("Sheet").PivotTables("PivotTable1").DataBodyRange

对于所有有总计但没有小计的列:

Set myRange = Worksheets("Sheet").PivotTables("PivotTable1").DataBodyRange
Set myRange = myRange.Resize(myRange.Rows.Count - 1, myRange.Columns.Count)

根据之前的回答,只是另一个函数的小实现,用于获取数据透视表 table 上特定列的最大值。您可以传递数据透视表 table 名称和字段名称。

Function getMaxPT(istrPTName As String, istrPTField As String) As Double
  ' Found the max value in a column from a pivot table
  ' Author: Mauricio Roa, mauricio_roa_f@yahoo.com
  ' Date: 2018-10-02

  Dim myRange As Range
  Dim pt As PivotTable
  Dim ws As Worksheet
  Dim bPTFounded As Boolean

  ' Search for the pivot table using the name
  bPTFounded = False
  For Each ws In ActiveWorkbook.Worksheets
      For Each pt In ws.PivotTables
          If pt.Name = istrPTName Then
              bPTFounded = True
              Exit For
          End If
      Next pt
      If bPTFounded Then Exit For
  Next ws

  ' If founded, calculate the maximum. If not found, result is undefined
  If bPTFounded Then
      Set myRange = pt.PivotFields(istrPTField).DataRange
      getMaxPT = Application.WorksheetFunction.max(myRange)
  End If
End Function

Sub getMaxPTTest()
    Dim x As Double

    x = getMaxPT("myPivotTable", "myPTColumnName")
End Sub