excelvbaexcel-formulaautomation

How to Sample Top 10 Largest Values in a PivotTable and insert in a separate table?


I'm a beginner in terms of using the automation feature for Excel. Now I have used the automate record feature to create PivotTables for a report. However, in the script it didn't sort the data from largest to smallest, which is my first problem. My second, is once I sort it manually, I would like to have an automation feature that would take the top 10 from 2 general categories in each PivotTable and insert them into tables on different sheets. However, sometimes these categories don't always have 10 values. Is it possible to limit the number of cells it copies and pastes to the tables?

enter image description here

enter image description here

I have an idea of what I could possibly do, I have tried inserting a formula to the Summary Table and utilizing the =GETPIVOTDATA function. However, I'm having trouble writing the formula and keep getting a reference error.

A formula that I have been trying is
=GETPIVOTDATA("Item Description",'KMA Summary2'!$A$3)

I have also tried
=GETPIVOTDATA("Con",'KMA Summary 2'!$A$3,"Item Description")

and...
=GETPIVOTDATA("Item Description",'KMA Summary 2'!$A$3,"Type","Con")

enter image description here


Solution

  • You could access the pivot table data, treating it as a range. Since the shape can change with the underlying data, you may want to include more rows (and columns) to the range. Here's an example - you may be able adopt it to your needs. If you're able to share more detailed samples, we may be able to get a better solution.

    =LET(
        pivot_headers, A4:D4,
        pivot_data, A5:D300,
        top_n, 10,
        result, TAKE(
            CHOOSECOLS(
                pivot_data,
                XMATCH({"Row Labels", "Dry Fruits"}, pivot_headers, 0)
            ),
            top_n
        ),
        result
    )
    

    Use of XMATCH: I prefer looking up column headers instead of just using column index provides context and also makes it more flexible.

    Since you seem to be comfortable looking up references, I'm not explaining LET, TAKE etc. :)

    Formula and result