2013-01-17 30 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

您正在使用「加拿大」,單元格具有「加拿大」(區分大小寫),因此無法找到它,因此它試圖隱藏所有的數據透視表項。當它到達最後一個樞紐項目,因爲你不能隱藏所有的樞軸項目,你得到的錯誤:) –