2017-08-01 51 views
0

我試圖展示基於一個下拉選項/隱藏樞紐項目。無法設置可見=假一次後隱藏樞紐項目 - Excel的VBA

如果你看到下面的代碼,細胞S3是一個下拉的選項 - 所有,一月,二月..十二月當我改變下拉,我想只顯示所選月份的樞軸項目。

這裏發生的事情是,一旦我設置的項目知名度假的,我不能夠做它再次可見。所以,下面簡單地每個迴路忽略前面已經

Private Sub Worksheet_Change(ByVal Target As Range) 

Dim pt As PivotTable, counter 
Dim pi As PivotItem, msg, mname 

Application.EnableEvents = False 

If Target.Address = "$S$3" Then 

    Application.EnableEvents = False 
    Set pt = Sheet3.PivotTables(1) 

    mname = Sheet2.Range("S3").Value 
    pt.RefreshTable 

    For Each pi In pt.PivotFields("Values").PivotItems 
     If InStr(pi, mname) > 0 Or mname = "All" Then 
      pi.Visible = True 
     Else 
      pi.Visible = False 
     End If 
    Next pi 
End If 

Application.EnableEvents = True 

End Sub 

Screenshot of my Pivot Table

+0

只是一個問題,爲什麼不使用切片機?它會做正是這一點,沒有VBA,它甚至看起來不錯 –

+0

我想過濾的x軸上的值。切片機不給我這個選項。 – Archana

+0

您在哪個工作表模塊中擁有此代碼? 'Sheet3'? 'Sheet2'?另一張紙? –

回答

0

隱藏試試下面的代碼(代碼爲commnets裏面的解釋)的項目:

Option Explicit 

Private Sub Worksheet_Change(ByVal Target As Range) 

Dim pt As PivotTable 
Dim pi As PivotItem 
Dim pf As PivotField 

Dim msg As String, mname As String 
'Dim counter ' <-- not used in this piece of code 

If Target.Address = "$S$3" Then 
    Application.EnableEvents = False 

    ' set the PivotTable object 
    Set pt = Sheet3.PivotTables(1) 

    mname = Target.Value ' <-- you can use the Target object 
    pt.RefreshTable 

    ' set the PivotField object 
    Set pf = pt.PivotFields("Values") 
    pf.ClearAllFilters ' clear all previous filters from "Values" 

    ' if value is "All", show all items, (no need to run the loop) 
    If mname <> "All" Then 
     For Each pi In pf.PivotItems 
      If Not pi.Name Like "*" & mname & "*" Then ' only if the value is not like the month >> hide the PivotItem 
       pi.Visible = False 
      End If 
     Next pi 
    End If 
End If 

Application.EnableEvents = True 

End Sub 
+0

感謝您的幫助。然而,我得到的應用程序錯誤的步驟 - pf.ClearAllFilters的' – Archana

+0

@Archana在哪一行你得到這個錯誤? –

+0

pf.ClearAllFilters – Archana