循环浏览报告filter以更改可见性不起作用

我试图select一个报告filter,在这种情况下,加拿大。 这意味着其余的必须是隐形的。 这段代码没有问题:

Public Sub FilterPivotTable() With ActiveSheet.PivotTables("Epidemiology").PivotFields("COUNTRY") .PivotItems("Canada").Visible = True .PivotItems("USA").Visible = False .PivotItems("Germany").Visible = False .PivotItems("France").Visible = False End With End Sub 

然而,我正在试图为将其他国家添加到我们的“stream行病学”数据透视表中做准备,所以我尝试了一个for循环。 此代码不起作用:

 With ActiveSheet.PivotTables("Epidemiology").PivotFields("COUNTRY") .PivotItems("Canada").Visible = True For Each Pi In .PivotItems If Pi.Value = "CANADA" Then Pi.Visible = True Else Pi.Visible = False End If Next Pi End With 

它给了我一个错误的Pi.Visible = False行。 我得到的错误是Run-time error '1004': Unable to set the Visible property of the PivotItem class

为什么不在for循环中工作?

令人沮丧的是,我在网上find的所有例子都使用类似的语法。 (有些使用索引,但是我试过了,得到了同样的错误。)

这是你正在尝试?

 Sub Sample() Dim Pi As PivotItem With ActiveSheet.PivotTables("Epidemiology").PivotFields("COUNTRY") .PivotItems("Canada").Visible = True For Each Pi In .PivotItems If UCase(Pi.Value) = "CANADA" Then Pi.Visible = True Else Pi.Visible = False End If Next Pi End With End Sub 

在可旋转的filter中,您必须始终至lessselect一个项目。 即使你打算在代码中稍后select一个。

 With Pt.PivotFields("COUNTRYSCENARIO") ' Sets all filters to true, resetting it. .ClearAllFilters ' This is necessary if you want to select any options ' other than "All Pivot Items = Visible" and ' "OnlyOneSpecificPivotItem = Visible" .EnableMultiplePageItems = True If .PivotItems.Count > 0 Then ' goofy but necessary Set firstPi = .PivotItems(1) For Each Pi In .PivotItems ' Make sure that that first pivot item is visible. ' It gets mad if it's already visible and you ' set it to visible with firstPi.Visible = True ' ...pretty silly If firstPi.Visible = False Then firstPi.Visible = True ' Don't loop through firstPi If Pi.Value <> firstPi.Value Then If Pi.Value = opt1 Or Pi.Value = opt2 Or Pi.Value = opt3 Then Pi.Visible = True ElseIf Pi.Visible = True Then Pi.Visible = False End If End If Next Pi ' Finally perform the check on the first pivot item If firstPi = opt1 Or firstPi = opt2 Or firstPi = opt3 Then firstPi.Visible = True Else firstPi.Visible = False End If End If End With 

请注意,如果您尝试不select任何内容,例如opt 1 =“”和opt2 =“”和opt3 =“”,则会出现相同的错误:必须至lessselect一个数据透视表项。