我正在尝试选择一个报告过滤器,在本例中为加拿大。这意味着其余部分必须是隐形的。 此代码可以正常运行:
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
但是,当我们将其他国家/地区添加到我们的“流行病学”数据透视表中时,我正在尝试做准备,所以我尝试了一个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循环中不起作用?!
令人沮丧的是,我在网上找到的所有示例都使用了类似的语法。 (有些人使用索引,但我尝试过并得到了同样的错误。)
答案 0 :(得分:7)
这是你在尝试的吗?
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
答案 1 :(得分:0)
在可旋转滤镜中,您必须始终至少选择一个项目。即使您打算稍后在代码中选择一个。
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
请注意,如果您尝试不选择任何内容,例如opt 1 =“”和opt2 =“”和opt3 =“”,您将遇到同样的错误:您必须至少选择一个透视图项目。