title: Filter Excel pivot table using VBA
body: <p>I have tried copying and pasting solutions from the internet forever now to try to filter a pivot table in Excel using VBA. The code below doesn't work.</p>
  
  <pre><code>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
  </code></pre>
  
  <p>I want to filter so I see all rows that have SavedFamilyCode K123223. I don't want to see any other rows in the pivot table. I want this to work regardless of the previous filters. I hope you can help me with this. Thanks!</p>
  
  <hr>
  
  <p>Based on your post I'm trying:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>Unfortunately I get Run time error 91: Object variable or With block variable not set. What has caused this error?</p>