如何使用VBA过滤Excel 2003中的数据透视表?
在Excel 2007中,我可以运行此宏,但在XL 2003中未实现PivotFilters。
Dim ws As Worksheet: Set ws = Sheets("Sheet1")
ws.PivotTables("PivotTable1").PivotFields("Date").PivotFilters.Add _
Type:=xlSpecificDate, Value1:="26/01/2012"
更新: 我收到错误“运行时错误'1004”。无法设置PivotItem类的Visible属性。
子过滤器() 昏暗的PvtItem作为PivotItem Dim Ws As Worksheet
Set ws = Sheets("pivot")
'~~> Show All
For Each PvtItem In ws.PivotTables("PivotTable1").PivotFields("Date").PivotItems
PvtItem.Visible = True
Next
'~~> Show Only the relevant
For Each PvtItem In ws.PivotTables("PivotTable1").PivotFields("Date").PivotItems
If PvtItem.Value <> "26/01/2012" Then PvtItem.Visible = False '<-- error here
Next
End Sub
答案 0 :(得分:2)
要在VBA 2003中过滤数据透视表,您必须设置/取消设置.Visible属性。这是一个例子
Option Explicit
Sub Filter()
Dim PvtItem As PivotItem
Dim ws As Worksheet
On Error GoTo Whoa1
Set ws = Sheets("pivot")
'~~> Show All
For Each PvtItem In ws.PivotTables("PivotTable1").PivotFields("Date").PivotItems
PvtItem.Visible = True
Next
On Error GoTo Whoa2 '<~~ If no match found in Pivot
'~~> Show Only the relevant
For Each PvtItem In ws.PivotTables("PivotTable1").PivotFields("Date").PivotItems
If Format(PvtItem.Value, "DD/MM/YYYY") <> Format(Range("today"), "DD/MM/YYYY") Then
PvtItem.Visible = False
End If
Next
Exit Sub
Whoa1:
MsgBox Err.Description
Exit Sub
Whoa2:
'~~> Show All
For Each PvtItem In ws.PivotTables("PivotTable1").PivotFields("Date").PivotItems
PvtItem.Visible = True
Next
End Sub