Excel VBA读取数据透视表并显示msgbox

时间:2016-12-15 14:39:12

标签: excel vba excel-vba pivot-table

我有一个数据透视表和下面的VBA,它显示第一行字段的msgbox,但是我需要它遍历显示每个字段的消息框的所有行字段,有人能指出我正确的方向,我似乎无法解决如何做到这一点

Sub Piv()

  Dim PvTable As PivotTable
  Dim PvField As PivotField
  Dim PvItem As PivotItem

  Set PvTable = ActiveSheet.PivotTables("RawDataTable")
  Set PvField = PvTable.RowFields(1)

  With ws
    For Each PvItem In PvField.PivotItems
      MsgBox PvItem

    Next
  End With

End Sub

我也可以让它给我所有的字段标题,但不是数据

Sub Piv()

  Dim PvTable As PivotTable
  Dim PvField As PivotField
  Dim PvItem As PivotItem

  Set PvTable = ActiveSheet.PivotTables("RawDataTable")

  With ws
    For Each PvField In PvTable.PivotFields
      MsgBox PvField

    Next
  End With

 End Sub

1 个答案:

答案 0 :(得分:1)

这是一种相当强力的方法,希望有人会提出更优雅的东西,但我们可以将行字段的详细信息读入数组数组,然后以反向索引顺序运行此数组:

Option Explicit

Sub Piv()

    Dim PvTable As PivotTable
    Dim PvField As PivotField
    Dim PvItem As PivotItem
    Dim dataArray() As Variant
    Dim dummyArray() As Variant
    Dim i As Long
    Dim j As Long

    Set PvTable = ActiveSheet.PivotTables("RawDataTable")

    ReDim dataArray(1 To PvTable.RowFields.Count)
    ReDim dummyArray(1 To PvTable.RowFields(1).PivotItems.Count)

    For i = 1 To PvTable.RowFields.Count
        dataArray(i) = dummyArray
        For j = 1 To PvTable.RowFields(i).PivotItems.Count
            dataArray(i)(j) = PvTable.RowFields(i).PivotItems(j)
        Next j
    Next i

    For i = 1 To UBound(dataArray(1))
        For j = 1 To UBound(dataArray)
            MsgBox dataArray(j)(i)
        Next j
    Next i

End Sub