如何使用vba筛选数据透视表以仅显示另一列中包含的值

如何使用vba筛选数据透视表以仅显示另一列中包含的值,vba,excel,pivot-table,Vba,Excel,Pivot Table,我正在尝试创建一个vba宏,该宏将过滤透视表,以便显示的唯一值也是其他工作表上项目列表中存在的值 透视表具有以下结构: Raw Material Item Code | other column1 | other column2 | ... etc. 1001 | | | 1002 | | |

我正在尝试创建一个vba宏,该宏将过滤透视表,以便显示的唯一值也是其他工作表上项目列表中存在的值

透视表具有以下结构:

Raw Material Item Code | other column1 | other column2 | ... etc.
       1001            |               |               |
       1002            |               |               |       
       10PT            |               |               |
         .             |               |               |
         .             |               |               |
         .             |               |               |
我想在“原材料项目代码”字段中放置一个过滤器

另一个表只是一个项目列表,从单独工作表上的A1开始,如下所示:

    A
1| 1001
2| 1234
3| 8123
4| 1004
5|   .
6|   .
7|   .
8|   .
基本上,我希望能够向列表中添加或删除项目,并自动筛选数据透视表,以便仅显示其“原材料项目代码”值与另一个列表中的项目匹配的项目

这是我目前的代码:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    Dim NewCat As String
    Dim col As New Collection
    Dim Pi As PivotItem

'   This is getting a collection of all of the values containted in the other table.

        Worksheets("test").Select
        Worksheets("test").Range("A1").Select

        Do Until ActiveCell.Value = ""
            NewCat = ActiveCell.Value
                col.Add (NewCat)
            ActiveCell.Offset(1, 0).Select
        Loop

'   This is interating through the Pivot Items in the Pivot Table and setting their visability to False.

        With Worksheets("Trim Inventory - NC-Obsolete").PivotTables("PivotTable2").PivotFields("Raw Material Item Code")
            For i = 1 To .PivotItems.Count - 1
                .PivotItems(.PivotItems(i).Name).Visible = False
            Next i

'   This is interating back through the Pivot Items in the Pivot Table and setting the visability of the items that exist in the 
'   other table to True.

             For i = 1 To .PivotItems.Count - 1
                For Each c In col
                    If UCase(.PivotItems(.PivotItems(i).Name).Value) = c Then
                        .PivotItems(.PivotItems(i).Name).Visible = False
                    End If
                Next c
            Next i

        End With

End Sub
当它运行时,它会过滤掉所有内容。有人能给我指一下正确的方向吗?我也愿意接受完整的代码更改建议,因为我知道这种方法可能不是最有效的方法。

试试这个

Sub partNum()
Dim pt As PivotTable

Set pt = Worksheets("Feuil4").PivotTables(1)
pt.PivotCache.op
pt.PivotCache.MissingItemsLimit = xlMissingItemsNone
End Sub

就我个人而言,我会添加一个带有countif()公式的helper列,然后过滤该列上大于零的透视表。您是否尝试过使用调试器逐行进行调试?我没有,这是一个好主意。我会调查的。