首页 文章

设置PivotItem.Visible = false时,无法设置PivotItem类的Visible属性

提问于
浏览
6

我想制作 PivotItem.Visible = False 但我一直收到错误:

无法设置PivotItem类的Visible属性

我尝试了在互联网上找到的所有解决方案,但似乎都没有

Sub FloorCompareSetter()

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

    Set PivotSheet = ThisWorkbook.Worksheets("PIVOT")
    PivotSheet.PivotTables("PivotTable5").RefreshTable

    Set pt = PivotSheet.PivotTables("PivotTable5")
    pt.PivotCache.MissingItemsLimit = xlMissingItemsNone

    Set pf = pt.PivotFields("Period")

    For Each pi In _
        pt.PivotFields("Period").PivotItems
        Select Case pi.Name
            Case Is = "1601A"
                pi.Visible = True
            Case Else
                pi.Visible = False 'error
        End Select
    Next pi

End Sub

我尝试刷新表格和这一行,但仍然无法正常工作:

pt.PivotCache.MissingItemsLimit = xlMissingItemsNone

这是我的数据透视表的图片:

enter image description here

我做错了什么,如何解决这个问题?

2 回答

  • 0

    如果您尝试隐藏任何轴(行,列,过滤器)上的所有项目,您将收到此错误 . 通过将 PivotField 对象的 HiddenItems.Count 属性与同一对象的 PivotItems.Count 属性进行比较,可以在代码中捕获此错误,并确保不要尝试从视图中删除该集合的最后一项:

    因此,在您的case语句中,您可以使用以下内容替换update:

    Select Case pi.Name
        Case Is = "1601A"
            pi.Visible = True
        Case Else
            If pf.HiddenItems.Count < (pf.PivotItems.Count - 1) Then
                pi.Visible = False 
            Else
                MsgBox "Cannot hide all the items on this axis"
                Exit For '<~~ break the loop to stop the MsgBox popping up
            End If
    End Select
    

    请注意,在操作数据透视表时,Excel不允许您从轴中删除最后一项 - “确定”按钮将被禁用:

    enter image description here

  • 7

    我补充道

    On Error Resume Next

    之前

    pi.Visible = False'错误

    它现在有效!

相关问题