我想这是一个简单的问题,但由于我是VBA的新手,我无法理解。
我将此代码转到Pivot table1
,选择DATA
数据透视字段并过滤此字段的某些值。
Sub Multiple_Filtering()
Dim pf As PivotField
Set pf = ActiveSheet.PivotTables("Pivot table1").PivotFields("DATA")
'Enable filtering on multiple items
pf.EnableMultiplePageItems = True
'Must turn off items you do not want showing
pf.PivotItems("201511").Visible = False
pf.PivotItems("201512").Visible = False
pf.PivotItems("201501").Visible = True
pf.PivotItems("201502").Visible = True
End Sub
我想要做的是为工作簿中所有工作表中的所有数据透视表创建一个循环。
我发现这段代码使用“For each”句子为工作簿中的所有数据透视表设置数据源,但我无法将其用于我的代码。
Dim sht As Worksheet
Dim pvt As PivotTable
For Each sht In ThisWorkbook.Worksheets
For Each pvt In sht.PivotTables
pvt.ChangePivotCache _
ThisWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=SourceAddress)
pvt.RefreshTable
Next pvt
Next sht
有什么想法吗?
答案 0 :(得分:2)
Sub Multiple_Filtering()
Dim pf As PivotField
Dim sht As Worksheet
Dim pvt As PivotTable
For Each sht In ThisWorkbook.Worksheets
For Each pvt In sht.PivotTables
Set pf = pvt.PivotFields("DATA")
'Enable filtering on multiple items
pf.EnableMultiplePageItems = True
'Must turn off items you do not want showing
pf.PivotItems("201511").Visible = False
pf.PivotItems("201512").Visible = False
pf.PivotItems("201501").Visible = True
pf.PivotItems("201502").Visible = True
Next pvt
Next sht
End Sub
答案 1 :(得分:1)
我相信这应该整合那里显示的两段代码
Sub Multiple_Filtering()
Dim sht As Worksheet
Dim pvt As PivotTable
Dim pf As PivotField
For Each sht In ThisWorkbook.Worksheets
For Each pvt In sht.PivotTables
Set pf = sht.PivotTables(pvt).Pivotfields("DATA")
'Enable filtering on multiple items
pf.EnableMultiplePageItems = True
'Must turn off items you do not want showing
pf.PivotItems("201511").Visible = False
pf.PivotItems("201512").Visible = False
pf.PivotItems("201501").Visible = True
pf.PivotItems("201502").Visible = True
'Admittedly not sure if this is necessary
pvt.RefreshTable
Next pvt
Next sht
End Sub