我想让 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
这是我的数据透视表的图片:
我做错了什么以及如何解决这个问题?
最佳答案
如果您尝试隐藏任何轴上的所有项目(行、列、过滤器),您将收到此错误。您可以通过将 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 不允许您从轴中删除最后一项 - “确定”按钮将被禁用:
关于vba - 设置 PivotItem.Visible = false 时无法设置 PivotItem 类的 Visible 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41257799/