【问题标题】:Unable to unhide pivot items after setting visible = false once - Excel VBA设置可见 = false 一次后无法取消隐藏数据透视项目 - Excel VBA
【发布时间】:2018-01-07 23:21:47
【问题描述】:

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

如果您看到下面的代码,单元格 S3 是一个带有选项的下拉列表 - All、Jan、Feb.. Dec。当我更改下拉列表时,我只想显示所选月份的数据透视项目。

这里发生的情况是,一旦我将项目可见性设置为 false,我就无法再次使其可见。因此,下面的 for each 循环只是忽略了之前隐藏的那些项目

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

【问题讨论】:

  • 只是一个问题,为什么不使用切片机?它会做到这一点,没有 VBA,甚至看起来不错
  • 我正在尝试过滤 x 轴上的值。 Slicer 没有给我这个选项。
  • 您在哪个工作表模块中有此代码? Sheet3 ? Sheet2 ?另一张纸?

标签: excel vba


【解决方案1】:

试试下面的代码(代码内的解释为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

【讨论】:

  • 感谢您的帮助。但是,我在步骤中收到应用程序错误 - pf.ClearAllFilters '
  • @Archana 您在哪一行收到此错误?
  • pf.ClearAllFilters
猜你喜欢
  • 2015-05-02
  • 1970-01-01
  • 1970-01-01
  • 2015-12-30
  • 1970-01-01
  • 1970-01-01
  • 2012-05-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多