设置visible = false一次后无法取消隐藏数据透视表项 - Excel VBA

时间:2017-08-01 07:49:39

标签: excel-vba vba excel

我正在尝试根据下拉选项显示/隐藏数据透视表项。

如果您看到下面的代码,则单元格S3是带有选项的下拉菜单 - 全部,1月,2月... 12月。当我更改下拉菜单时,我只想显示所选月份的数据透视项目。

这里发生的事情是,一旦我将项目可见性设置为false,我就无法再次显示它。因此,下面的每个循环都会忽略那些之前隐藏的项目

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

1 个答案:

答案 0 :(得分: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