gpt4 book ai didi

excel - 循环遍历已过滤的枢轴项目

转载 作者:行者123 更新时间:2023-12-04 20:52:29 25 4
gpt4 key购买 nike

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

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

field 安排:

enter image description here

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

enter image description here

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

enter image description here

如图所示,所有项目都被选中,因此当从枢轴字段循环遍历所有“可见”枢轴项目时,它将循环遍历 5 次,因为有 5 个不同的项目。然而,在这个例子中,在我做了一些过滤之后,我最终只得到了 1 个行标签,所以它应该只针对数据透视表中存在的内容循环一次。我在这里做错了什么?

最佳答案

您需要查看 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

关于excel - 循环遍历已过滤的枢轴项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55118375/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com