[英]Excel VBA read pivot table and display msgbox
I have a pivot table and the following VBA which displays a msgbox for the first row field, but I need it to go through all row fields displaying a message box for each one, can someone point me in the right direction, I cant seem to work out how to do it 我有一个数据透视表和下面的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
I can also get it to give me all the field headers, but not the data 我也可以得到所有字段标题,但没有数据
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
This is a fairly brute-force approach, and hopefully someone will come up with something more elegant, but we can read the details of the row fields into an array of arrays, and then run through this array in reverse index order: 这是一种蛮力的方法,希望有人会提出一些更优雅的方法,但是我们可以将行字段的详细信息读入一个数组数组,然后以相反的索引顺序遍历该数组:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.