【问题标题】:Dynamic VBA macro to hide all pivot table values用于隐藏所有数据透视表值的动态 VBA 宏
【发布时间】:2019-11-09 00:34:57
【问题描述】:

寻找一种动态且快速的方法来隐藏所有数据透视表值。到目前为止,我有下面的代码,但这仅在没有任何新值的情况下才有效(例如:如果将帐户“333”添加到数据中,则脚本会中断)。有什么建议吗?

Sub Hide_Accounts()
   With ActiveSheet.PivotTables("PivotTable2").PivotFields("Account")
       .PivotItems("000").Visible = False
       .PivotItems("111").Visible = False
       .PivotItems("222").Visible = False
       .PivotItems("(blank)").Visible = False
   End With
End Sub

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    AFAIK 你不能隐藏一个字段中的所有项目(这会引发错误)。另一种方法是隐藏整个字段。

    尝试此代码并阅读 cmets 以根据您的需要进行调整:

    Sub Hide_Accounts()
    
        Dim evalPivotTable As PivotTable
        Dim evalPivotField As pivotField
    
        Dim targetSheetName As String
        Dim targetPivotTableName As String
        Dim targetPivotFieldName As String
    
        ' Define the names of sheet and pivot table
        targetSheetName = "Sheet1"
        targetPivotTableName = "PivotTable2"
        targetPivotFieldName = "Account"
    
        Set evalPivotTable = ThisWorkbook.Worksheets(targetSheetName).PivotTables(targetPivotTableName)
    
        ' Loop through all pivot table fields
        For Each evalPivotField In evalPivotTable.PivotFields
    
            If evalPivotField.Name = targetPivotFieldName And evalPivotField.Orientation <> xlHidden Then
                ' Hide the field
                evalPivotField.Orientation = xlHidden
    
                ' You can exit the loop because you have hidden the entire field
                Exit For
    
            End If
    
        Next evalPivotField
    
    End Sub
    

    如果对你有帮助,记得标记答案。

    【讨论】:

    • 也许你可以使用 .ShowDetail 属性。看here
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多