循环浏览已过滤的枢纽项目

时间:2019-03-12 09:44:47

标签: excel vba

我试图将数据透视表的数据值复制到另一个工作表中,但是因为当我遍历数据透视表字段的数据透视表项时,我会在数据透视表中进行过滤,从而“隐藏”了一些行标签在行标签中,它循环的次数比实际次数多。为了说明我的问题,这里是我使用的代码。

Sub Prob()
Dim Ptable1 as PivotTable
Dim PField as PivotField
Dim PField2 as PivotField
Dim NumOfPItem as Long
Dim PItem as PivotItem
Dim aCell as Range

Set Ptable1 = ActiveSheet.PivotTables("PivotTable1")

With Ptable1.PivotFields("DataCol5")
    .CurrentPage = "12/2/2018"
End With

PField = Ptable1.PivotFields("DataCol1")
NumOfPItem = PField.PivotItems.Count

For each PItem in PField.PivotItems
   'Some code to get a cell reference in another worksheet

   'and then some code to copy the value from the pivot table to cells.
   aCell.Offset(0,1).Value = PField2.PivotItems("XX01").DataRange.Cells(PItem.Position,1)
Next PItem
End Sub

我只是准备了一些简单的东西,以便它可以解决我面临的主要问题。

enter image description here

未过滤的数据透视表:

enter image description here

现场安排:

enter image description here

这是过滤后的数据透视表。

enter image description here

我尝试遍历使用PivotItems.Visible属性可见的枢纽项目,但这些项目都是可见的,因此遍历存在的每个枢纽项目。转到我的下一个屏幕截图。

enter image description here

可以看到,所有项目都被选中,因此当遍历数据透视域中所有“可见”的透视数据时,由于存在5个不同的数据,它将遍历5次。但是,在此示例中,我进行了一些过滤后,最终只得到了1行标签,因此对于数据透视表中存在的内容,它应该仅循环一次。我在这里做什么错了?

2 个答案:

答案 0 :(得分:0)

您需要查看pivotitem是否可见。另外,我注意到您正在使用PI,这可能会与PI混淆,因此在进行更改时值得。

这是一个例子

Sub x()

Dim p As PivotTable
Dim pf As PivotField
Dim pit As PivotItem

Set p = ActiveSheet.PivotTables(1)
Set pf = p.PivotFields("Name")

For Each pit In pf.PivotItems
    Debug.Print pit.Visible
Next pit

End Sub

答案 1 :(得分:0)

Sub Solution()
Dim Ptable1 as PivotTable
Dim PField as PivotField
Dim PField2 as PivotField
Dim NumOfRows as Long
Dim PItem as PivotItem
Dim aCell as Range
Dim PFRng as Range
Dim i as long

Set Ptable1 = ActiveSheet.PivotTables("PivotTable1")

With Ptable1.PivotFields("DataCol5")
    .CurrentPage = "12/2/2018"
End With

PField = Ptable1.PivotFields("DataCol1")
PFRng = PField.DataRange
NumOfRows = PFRng.Rows.Count

For i = 1 to NumOfRows
   'Some code to get a cell reference in another worksheet

   'and then some code to copy the value from the pivot table to cells.
   aCell.Offset(0,1).Value = PField2.PivotItems("XX01").DataRange.Cells(i,1)
Next i
End Sub

我找到了解决方案。我不会遍历在透视字段中找到的每个透视项目,而只是获取透视字段的数据范围,查找数据范围中有多少行,然后从1到最后一行遍历。这样,我就不必担心什么是可见的。我可以使用“ i”代替数据透视表项的位置,以获取同一行中不同字段中的值。

相关问题