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

时间:2015-07-16 19:25:00

标签: excel vba excel-vba excel-2010 pivot-table

我有以下代码:

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属性”和debug highlight的行“Field.CurrentPage = NewCat”。

有关为何以及如何使此代码生效的任何见解都会很棒。

1 个答案:

答案 0 :(得分:0)

这是更新后的代码

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