2016-12-15 76 views
0

我有一個數據透視表和下面的VBA顯示第一行字段的msgbox,但我需要它通過顯示每個消息框的所有行字段,可以有人點我在正確的方向,我似乎無法找出如何做到這一點Excel 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

我可能失去了一些東西,但在第一個例子中,你能不能換你的'For'循環在另一個'For'循環中:'對於PvTable.RowFields中的每個PvField' – bobajob

+0

這有效,但它循環錯誤,它給了我所有的第一列數據,然後第二列等等,但我想穿過整行然後移動到下一個 – Jeffrey

+0

出於好奇,這些消息框的意圖是什麼?用戶在每個顯示器後都需要做什麼?你會給用戶一種退出程序的途徑嗎? – jeffreyweir

回答

1

這是一個相當強悍的方法,並希望有人會想出更優雅的東西,但我們可以閱讀詳細信息行字段到一個數組的數組的ILS,然後通過這個數組中的反向索引順序運行:

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