2013-01-17 31 views
4

我试图选择一个报告过滤器,在这种情况下是加拿大。这意味着其余部分必须隐形。 此代码的工作没有问题:循环显示报告过滤器以更改可见性不起作用

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

在一个可旋转的过滤器中,您必须始终至少选择一个项目。即使你打算在代码中稍后选择一个。

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 =“”,您将会遇到同样的错误:您必须至少选择一个透视项。

+0

@ user1507455嗨,我试了相同的代码。但它不适合我。你可以请解决它:http://stackoverflow.com/questions/38571986/error-1004-unable-to-set-the-visible-property-of-the-pivotitem-class – Pramod

+0

@SiddharthRout你能帮忙吗? – Pramod

6

这是你正在尝试?

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 
+0

这使它工作!谢谢!不完全确定您的更改会如何影响错误“无法设置PivotItem类的Visible属性”,但如果它起作用,请不要修复它。 – user1507455

+0

您正在使用“加拿大”,单元格具有“加拿大”(区分大小写),因此无法找到它,因此它试图隐藏所有的数据透视表项。当它到达最后一个枢纽项目,因为你不能隐藏所有的枢轴项目,你得到的错误:) –