根据单元格中的文本字符串过滤数据透视表 Table

Filtering a Pivot Table based on text string in a cell

我有以下代码:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Intersect(Target, Range("K2:K3")) Is Nothing Then Exit Sub

    Dim pt As PivotTable
    Dim Field As Variant
    Dim NewCat As String
    Set pt = Worksheets("Fact Trans").PivotTables("PivotTable1")
    Set Field = pt.PivotFields("[Locations].[Loc Name].[Location Name]")
    NewCat = Worksheets("Fact Trans").Range("K2").Value
    With pt
        Field.ClearAllFilters
        Field.CurrentPage = NewCat
        pt.RefreshTable
    End With

End Sub

如您所见,我正在尝试根据 K2 中的值更改我的数据透视表 table,但我不断收到错误 "Run-time error '1004': Unable to set CurrentPage property of the PivotField class" 并调试突出显示的行 "Field.CurrentPage = NewCat" .

任何关于为什么以及如何让这段代码工作的见解都会很棒。

这是更新后的代码

Private Sub Worksheet_SelectionChange(ByVal Target As Range)


If Intersect(Target, Range("K2:K3")) Is Nothing Then Exit Sub

Dim pt As PivotTable

Dim Field As Variant

Dim NewCat As String


Set pt = Worksheets("Fact Trans").PivotTables("PivotTable1")

Set Field = pt.PivotFields("[Locations].[Loc Name].[Location Name]")

NewCat = Worksheets("Fact Trans").Range("K2").Value


With ActiveSheet.PivotTables("PivotTable1").PivotFields("[Locations].[Loc Name].[Location Name]")
    .ClearAllFilters

.PivotFilters.Add Type:=xlCaptionEquals, Value1:=ActiveSheet.Range("K3").Value

End With

End Sub