从一个表中应用多个数据透视表过滤器

时间:2018-10-15 20:57:12

标签: excel vba filter pivot-table

我正在尝试根据表中的值列表过滤数据透视表。

Table2:
Selected Months    Selected Years
9                  2018
6   

数据透视表上过滤器的可用值依次为8、9、6和3。

我正在尝试使用以下代码:

    Sub ReportMonth()

    Dim pt1 As PivotTable
    Dim tbl As ListObject
    Dim x As Long
    Dim y As Long

       Set tbl = Worksheets(6).ListObjects("Table2")
       Set pt1 = Worksheets(5).PivotTables("PivotTable3")

   'Clear the pivot cache and clear the pivot filter choices of old data.
   'Enable multiple filter selections

    pt1.PivotCache.MissingItemsLimit = xlMissingItemsNone
    pt1.PivotCache.Refresh
    pt1.PivotFields("Month").EnableMultiplePageItems = True

    'y is the counter for Pivot filter items.
    'x is the counter for rows in Table 2 

    With pt1.PivotFields("Month")

            .ClearAllFilters

            On Error Resume Next

            For x = 1 To tbl.Range.Rows.Count
               For y = 1 To .PivotItems.Count
                      If .PivotItems(y).Name = tbl.DataBodyRange(x, 1).Value Then _
                        .PivotItems(y).Visible = True Else _
                        .PivotItems(y).Visible = False

               Next y
            Next x

   End With

End Sub

使用上面的代码,过滤器名称“ 3”可见,但表中甚至没有3。如果将.PivotItems(y).Name更改为.PivotItems(y).Value,则会得到相同的结果。如果我从For y = 1更改为For y =2,则过滤器名称“ 8”是可见的,并且不在表中。

我在for循环中放置了一个消息框,以返回x和y的值以及相应的过滤器和表值。这些正在按预期执行。

有人知道我该怎么做吗?

0 个答案:

没有答案
相关问题