【问题标题】:Excel VBA: How to use an Array as Filter Criteria for a Pivot TableExcel VBA:如何使用数组作为数据透视表的筛选条件
【发布时间】:2020-07-01 03:06:23
【问题描述】:

我每个月都会生成一份报告,其中显示了当月销售的所有采购订单的短缺和过剩情况。我正在构建一个宏,它以一种仅显示哪些发票超额的方式格式化数据。我已经构建了大部分宏来动态工作,但我的方式只有一个问题。在活动工作表上有 2 个数据透视表,数据透视表 1 被过滤为仅显示超额发票,因此我继续编写代码以将所有值存储在 ArrayA 中。现在我需要 PivotTable2 的 PivotField("Inv") 来显示 ArrayA 中的发票。我现在运行的代码,但它只是遍历该字段中的每个数据透视项并将其隐藏。在决定是否隐藏或显示 Pivot Item 时检查的值似乎存在问题,或者我认为我合并 Array 的方式不正确。无论如何,这是我的代码:

Sub OverageArray()

Dim ArrayA() As Variant
Dim Counter As Integer
Dim RowCount As Long

Dim PT As PivotTable
Dim PTItm As PivotItem

Set PT = ActiveSheet.PivotTables("PivotTable2")

RowCount = (Range("A1048576").End(xlUp).Offset(-1, 0).Row - 3)

ReDim ArrayA(RowCount)

    'For Loop that Builds the Array
    For Counter = 0 To RowCount
        ArrayA(Counter) = Cells((Counter + 4), 1).Value
    Next

    'This Filters the Pivot Field Based on the Array's Values
    For Each PTItm In PT.PivotFields("Inv#").PivotItems
        If Not IsError(Application.Match(PTItm.Caption, ArrayA, 0)) Then ' check if current item is not in the filter array
            PTItm.Visible = True
        Else
            PTItm.Visible = False
        End If
    Next PTItm

End Sub

【问题讨论】:

    标签: arrays excel vba pivot-table


    【解决方案1】:

    好消息,我已经在路上解决了。

    事实证明,将 ArrayA() 声明为变体将值保存为整数,并且此代码似乎仅在将值存储为字符串时才有效。所以我所要做的就是将 ArrayA() 声明为 String 而不是 Variant,以便它将所有值保存为字符串而不是整数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-14
      • 2013-07-02
      • 2021-11-30
      • 1970-01-01
      • 2012-02-20
      • 2020-11-22
      相关资源
      最近更新 更多