更新时间:2023-10-12 22:47:58
Field.CurrentPage 仅适用于过滤器字段(也称为页面字段).
如果要过滤行/列字段,则必须循环浏览各个项目,如下所示:
Field.CurrentPage only works for Filter fields (also called page fields).
If you want to filter a row/column field, you have to cycle through the individual items, like so:
Sub FilterPivotField(Field As PivotField, Value)
Application.ScreenUpdating = False
With Field
If .Orientation = xlPageField Then
.CurrentPage = Value
ElseIf .Orientation = xlRowField Or .Orientation = xlColumnField Then
Dim i As Long
On Error Resume Next ' Needed to avoid getting errors when manipulating PivotItems that were deleted from the data source.
' Set first item to Visible to avoid getting no visible items while working
.PivotItems(1).Visible = True
For i = 2 To Field.PivotItems.Count
If .PivotItems(i).Name = Value Then _
.PivotItems(i).Visible = True Else _
.PivotItems(i).Visible = False
Next i
If .PivotItems(1).Name = Value Then _
.PivotItems(1).Visible = True Else _
.PivotItems(1).Visible = False
End If
End With
Application.ScreenUpdating = True
End Sub
然后,您只需调用:
FilterPivotField ActiveSheet.PivotTables("PivotTable2").PivotFields("SavedFamilyCode"), "K123223"
当然,该领域中的不同项目越多,这会变得越慢.如果更适合您的需要,您也可以使用 SourceName 而不是 Name.
Naturally, this gets slower the more there are individual different items in the field. You can also use SourceName instead of Name if that suits your needs better.