[英]VBA macro to change filters in pivot table
I'm trying do automate a daily report and therefore I want to create two buttons which change the filters of three pivot tables. 我正在尝试自动化每日报告,因此我想创建两个按钮来更改三个数据透视表的过滤器。 In detail the buttons shall change the day which is shown. 详细信息按钮应更改显示的日期。 The first filters on yesterday the second one is a reset button do clear all filters and show all days. 昨天的第一个过滤器第二个是重置按钮确实清除所有过滤器并显示所有日期。 The "Resest"-Button is working but the "Yesterday"-Button not. “Resest”-Button正在运作,但“昨天” - 但不是。
At the moment the macro looks like that: 目前宏看起来像这样:
Private Sub CommandButton2_Click()
MsgBox ActiveSheet.Range("B1")
With ActiveSheet.PivotTables("Detail_Digital").PivotFields("Tag").CurrentPage = _
ACtiveSheet.Range("B1").Value
End With
End Sub
I've also tried PivotFilters.Add _ , Type:=xlDateYesterday
but that isn't working either. 我也尝试过PivotFilters.Add _ , Type:=xlDateYesterday
但这也不起作用。
Any suggestions? 有什么建议么?
Try the code below, it should work, unless your "Date" is formatted differently between the Pivot's data source and Range("B1")
. 尝试下面的代码,它应该工作,除非您的“日期”在数据透视表的数据源和Range("B1")
之间的格式不同。
Note : try to avoid using ActiveSheet
, instead use referenced objects. 注意 :尽量避免使用ActiveSheet
,而是使用引用的对象。 In the case below, replace Worksheets("Sheet1")
with your sheet's name. 在下面的情况中,将Worksheets("Sheet1")
替换为Worksheets("Sheet1")
表的名称。
Code 码
Option Explicit
Private Sub CommandButton2_Click()
Dim PvtTbl As PivotTable
Dim PvtItm As PivotItem
' set the Pivot Table
Set PvtTbl = Worksheets("Sheet1").PivotTables("Detail_Digital")
With PvtTbl
.PivotFields("Tag").ClearAllFilters ' <-- clear all filters to "Tag"
'Debug.Print Worksheets("Sheet1").Range("B1").Value
For Each PvtItm In .PivotFields("Tag").PivotItems
If PvtItm.Name = Worksheets("Sheet1").Range("B1").Value Then
PvtItm.Visible = True
Else
PvtItm.Visible = False
End If
Next PvtItm
End With
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.