如何使用vba

时间:2016-03-09 21:53:06

标签: excel vba excel-vba pivot-table

我正在尝试创建一个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

当它运行时,它只是过滤掉所有内容。有人可以指点我正确的方向吗?我也对完整的代码更改建议持开放态度,因为我理解这种方法可能不是最有效的方法。

1 个答案:

答案 0 :(得分:0)

试试这个

Sub partNum()
Dim pt As PivotTable

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