Search code examples
vbaexcelpivot-tableolap

Run Macro after OLAP Query


This is my Workbook:

Sheets layout:

  1. Source: Pivot Table with Analysis Services connection
  2. Distributors: Stuff to be sorted connected with the Pivot
  3. Output: Chart based on sorted data of Distributors + Slicers connected to Pivot

What I need to do is: Launch Sorting Macro after each OLAP Query (= each time I use the slicers).

Sorting Code

Sub Sorting()

'This line finds the last occupied row in column A
'And you can use that LR variable in all the following Range Statements.
LR = Cells(Rows.Count, "C").End(xlUp).Row


    ActiveWorkbook.Worksheets("Distributors").Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("Distributors").Sort.SortFields.Add Key:=Range("C4:C102" & LR) _
        , SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
    With ActiveWorkbook.Worksheets("Distributors").Sort
        .SetRange Range("A3:C102" & LR)
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
    
        ActiveWorkbook.Worksheets("Distributors").Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("Distributors").Sort.SortFields.Add Key:=Range("D4:D102") _
        , SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
    With ActiveWorkbook.Worksheets("Distributors").Sort
        .SetRange Range("D3:F102")
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
End Sub

Solution

  • Solved. Launch Macro after each Pivot Update

    1. Alt+F11, Right click on Source (Sheet with PivotTable)
    2. View Code
    3. Insert the Event trigger

    Event Trigger

    Private Sub Worksheet_PivotTableUpdate(ByVal Target As PivotTable)
    'your_macro_here
    End Sub
    

    Keep in mind that you can't enter reference to a Module. Insert directly your macro.