gpt4 book ai didi

excel - 使用 VBA 筛选 Excel 数据透视表

转载 作者:行者123 更新时间:2023-12-01 21:19:37 25 4
gpt4 key购买 nike

我现在一直尝试从互联网上复制和粘贴解决方案,以尝试使用 VBA 过滤 Excel 中的数据透视表。下面的代码不起作用。

Sub FilterPivotTable()
Application.ScreenUpdating = False
ActiveSheet.PivotTables("PivotTable2").ManualUpdate = True
ActiveSheet.PivotTables("PivotTable2").PivotFields("SavedFamilyCode").CurrentPage = "K123223"
ActiveSheet.PivotTables("PivotTable2").ManualUpdate = False
Application.ScreenUpdating = True
End Sub

我想要进行筛选,以便看到包含 SavedFamilyCode K123223 的所有行。我不想在数据透视表中看到任何其他行。我希望无论以前的过滤器如何,它都可以工作。我希望你能帮我解决这个问题。谢谢!

<小时/>

根据你的帖子,我正在尝试:

Sub FilterPivotField()
Dim Field As PivotField
Field = ActiveSheet.PivotTables("PivotTable2").PivotFields("SavedFamilyCode")
Value = Range("$A$2")
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 fields 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

不幸的是,我收到运行时错误 91:未设置对象变量或 With block 变量。是什么导致了这个错误?

最佳答案

Field.CurrentPage 仅适用于筛选字段(也称为页面字段)。
如果要过滤行/列字段,则必须循环浏览各个项目,如下所示:

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。

关于excel - 使用 VBA 筛选 Excel 数据透视表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11071662/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com