VBA Excel从数据透视表中获取最大值

时间:2018-07-20 14:31:28

标签: vba excel-2010

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

例如

行标签|资源总和

第1行:22

第2行:30

第3英寸15

由于30是最大值,它将显示第2行。

我在这里

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

3 个答案:

答案 0 :(得分:0)

要获取特定字段的值,应遍历其单元格。然后进行一些比较以获取最大值。这将返回数据透视表中所有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

答案 1 :(得分:0)

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

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

数据:

data


结果:

localMax = 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)

答案 2 :(得分:0)

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

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