Macro to filter a pivot table by selected cell

MPBJR

Board Regular
Joined
Mar 28, 2007
Messages
143
Hi,
I have a Pivot table summary in worksheet sheet1 with a list of customer names in column "A" with sales by month in columns b-f. There is a filter in the pivot table by customer name in column "A".
Worksheet sheet2 has a list of detailed orders with the customer name in column "B".
What I'd like to do is simply select a customer name cell in worksheet 2 , and when I click the macro button, go to worksheet sheet1 and have it filter the pivot table to the customer name I selected in worksheet2. The pivot table name is simply "CUSTOMERS".

I've searched the web and this site for something similar and can not find anything that works.
Any help would be much appreciated.

thank you
 

Excel Facts

Format cells as date
Select range and press Ctrl+Shift+3 to format cells as date. (Shift 3 is the # sign which sort of looks like a small calendar).
Try this.
In this line of the macro write the name of the customer field.
Rich (BB code):
With ActiveSheet.PivotTables("CUSTOMERS").PivotFields("Customer")

VBA Code:
Sub filter_pivot_table()
  Dim sName As String, pItem As PivotItem, n As Long
  
  If ActiveCell.Value = "" Or ActiveCell.Column <> 2 Then
    MsgBox "Select a customer name"
    Exit Sub
  End If
  
  sName = ActiveCell.Value
  Sheets("Sheet1").Select
  With ActiveSheet.PivotTables("CUSTOMERS").PivotFields("Customer")
    .ClearAllFilters
    For Each pItem In .PivotItems
      If pItem <> sName Then
        n = n + 1
        If n < .PivotItems.Count Then
          pItem.Visible = False
        Else
          .ClearAllFilters
          MsgBox "The name does not exist"
        End If
      End If
    Next
  End With
End Sub
 
Upvote 0
I'm glad to help you. Thanks for the feedback.
 
Upvote 0

Forum statistics

Threads
1,214,978
Messages
6,122,549
Members
449,089
Latest member
davidcom

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top