1
votes

How do I filter a pivot table in Excel 2003 using VBA?

In Excel 2007 I can run this macro but PivotFilters are not implemented in XL 2003.

Dim ws As Worksheet: Set ws = Sheets("Sheet1")
ws.PivotTables("PivotTable1").PivotFields("Date").PivotFilters.Add _
        Type:=xlSpecificDate, Value1:="26/01/2012"

Update: I get an error "Run-time error '1004". Unable to set the Visible property of the PivotItem class.

Sub Filter() Dim PvtItem As 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

http://wikisend.com/download/426518/pivot.xls

1

1 Answers

2
votes

To filter a PivotField in VBA 2003, you have to set/unset the .Visible Property. here is an example

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