【问题标题】:Filtering a Pivot Table based on text string in a cell根据单元格中的文本字符串过滤数据透视表
【发布时间】:2015-07-16 19:25:00
【问题描述】:

我有以下代码:

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”。

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

【问题讨论】:

  • 通常,当您使用 With 块时,您需要在属于该父对象的对象前面加上前导 .
  • chrismas007 是什么意思?
  • 查看示例中的This Link
  • 现在我得到运行时错误'438':对象不支持这个属性或方法,我迷路了哈哈@Chrismas007
  • 说实话,看了你的代码后,我认为你甚至不需要WithEnd With 行...

标签: vba excel excel-2010 pivot-table


【解决方案1】:

这是更新后的代码

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

【讨论】:

    猜你喜欢
    • 2017-04-10
    • 2017-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-04
    • 2021-12-19
    • 1970-01-01
    相关资源
    最近更新 更多