繁体   English   中英

Excel VBA:如何使用数组作为数据透视表的筛选条件

[英]Excel VBA: How to use an Array as Filter Criteria for a Pivot Table

我每个月都会生成一份报告,显示当月售出的所有 PO 的短缺和超额情况。 我正在构建一个宏,它以某种方式格式化数据以仅显示哪些发票上有超额。 我已经构建了大部分宏来动态工作,但我的方式中只有一个问题。 在活动工作表上有 2 个数据透视表,数据透视表 1 被过滤以仅显示带有超额的发票,所以我继续编写代码以将所有值存储在 ArrayA 中。 现在我需要 PivotTable2 的 PivotField("Inv") 来显示 ArrayA 中的发票。 我现在运行的代码只是遍历该字段中的每个 Pivot 项并将其隐藏。 当它决定是否隐藏或显示 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

好消息,我能在路上弄明白。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM