Search code examples
excelvbaeventsslicers

Worksheet_change event and slicer filter connection conflict


I have a problem that is breaking my head for a couple of days now, so I decided to share it with you, maybe you already stumbled upon the same problem.

=== this is the context: ===

I'm working on this excel file where I have, among other, these three tabs: - one, called "Data", where I store the data I need for the file in a regular table; - the second, called "Chart_1", where one can find pivot_table_1 and chart_1. The source for these objects is in "Data" tab. - the third tab is called "Chart_2" and contains pivot_table_2 and chart_2. These objects are also sourced from "Data" tab. I have five slicers in tab "Chart_1" and another five in tab "Chart_2". All the slicers are connected to both pivot_tables found in the "Chart*" tabs. I used VBA for the charts formats in the tabs, as Worksheet_Change events.

=== this is the problem: ===

When I select something in the slicer (whichever is the "Chart*" tab), it always activates "Chart_2". If I click in one of the slicers in tab "Chart_1", when the macros finish running, tab "Chart_2" is activated. When I click in one of the slicers in tab "Chart_2", everything is fine because the activated tab doesn't change. Whichever slicer I use (whatever tab is it embedded in), VBA always runs first "Chart_1"'s Worksheet_Change and then "Chart_2"'s Worksheet_Change. I think this is happening because of the filter connections: when I click in one slicer, it will trigger all affected Worksheet_Change events.

=== this is what I already tried: ===

  • have a global variable where I store the name of the correspondent tab of the work. Didn't work because both macros from both tabs are executed. I tried the same with a counter and failed likewise.
  • look for a OnClick event where I could save the name of the tab where I clicked for the last time prior to the "Chart*"'s macros run. Didn't find any OnClick event, buh.
  • I thought about having a global variable to store the name of the sheet of the slicer I clicked/selected the last time, but I don't know how to get it. Do you think this could work? How can I implement it?

So, this is my logic/programming problem, right now. Do you have any suggestion on how can I fix it? I just want to stay in the tab where I was when I clicked the slicer...


Solution

  • As discussed in the comments:

    Chart1-Sheet:

    Public GoodNameForAVariable As String
    
    Private Sub Worksheet_Change(ByVal Target As Range)
    
    GoodNameForAVariable = ActiveSheet.Name
    
    'Your code happens here
    
    End Sub
    

    Chart2-Sheet:

    Private Sub Worksheet_Change(ByVal Target As Range)
    
    'Your code happens here
    
    ThisWorkbook.Sheets(GoodNameForAVariable).Activate
    
    End Sub