[英]How to filter PivotTable to only show values contained in another column using vba
I am trying to create a vba macro that will filter a pivot table so that the only values that show are the ones that also exist in a list of items on another worksheet. 我正在尝试创建一个vba宏,该宏将过滤数据透视表,以使显示的唯一值是另一个工作表上的项目列表中也存在的值。
The pivot table has the following construction: 数据透视表的结构如下:
Raw Material Item Code | other column1 | other column2 | ... etc.
1001 | | |
1002 | | |
10PT | | |
. | | |
. | | |
. | | |
I am wanting to place a filter on the "Raw Material Item Code" Field. 我想在“原始物料项目代码”字段上放置一个过滤器。
The other table is simply a list of items, starting at A1 on a separate worksheet that looks like this: 另一个表只是项目列表,从另一个工作表上的A1开始,如下所示:
A
1| 1001
2| 1234
3| 8123
4| 1004
5| .
6| .
7| .
8| .
Essentially, I want to be able to add or remove items to the list and have the PivotTable automatically filtered to show only the items where it's "Raw Material Item Code" value matches an item in the other list. 本质上,我希望能够添加或删除列表中的项目,并自动对数据透视表进行过滤,以仅显示其“原始物料项目代码”值与其他列表中的项目匹配的项目。
Here is my current code: 这是我当前的代码:
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
When this runs, it just filters out everything. 运行时,它只会过滤掉所有内容。 Can someone please point me in the correct direction?
有人可以指出正确的方向吗? I am also open for complete code change suggestions seeing as how I understand that this approach may not be the most efficient one.
我也乐于接受完整的代码更改建议,因为我了解到这种方法可能不是最有效的方法。
try this 尝试这个
Sub partNum()
Dim pt As PivotTable
Set pt = Worksheets("Feuil4").PivotTables(1)
pt.PivotCache.op
pt.PivotCache.MissingItemsLimit = xlMissingItemsNone
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.