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

标签 vba excel pivot-table

我想让 PivotItem.Visible = False 但我不断收到错误:

Unable to set the Visible property of the PivotItem class

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

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

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

最佳答案

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

因此,在您的案例陈述中,您可以将 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

关于vba - 设置 PivotItem.Visible = false 时无法设置 PivotItem 类的 Visible 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41257799/

相关文章:

hadoop - 在不使用自定义UDF或左联接的情况下如何在Hive中进行关键操作?

Excel反向替换

php - 使用 PEAR 从数据库生成 Excel

excel - 如何在VBA中安排邮件发送到特定时间

excel - 如何使用vba从具有多个数据字段的Excel数据透视表中删除小计

vba - 如何将 Excel 切片器链接到 Excel slider (滚动条)?

excel - VBA有Hash_HMAC吗

excel - 为什么这里似乎忽略了 VBA 错误处理?

sql - 在 Windows 7 64 位上找不到提供程序

laravel - 在 laravel 中通过 id 更新数据透视表