簡體   English   中英

根據單元格中的文本字符串篩選數據透視表

[英]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中的值更改數據透視表,但始終收到錯誤“運行時錯誤'1004':無法設置PivotField類的CurrentPage屬性”並調試突出顯示的行“ 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM