• Hi All

    Please note that at the Chandoo.org Forums there is Zero Tolerance to Spam

    Post Spam and you Will Be Deleted as a User

    Hui...

  • When starting a new post, to receive a quicker and more targeted answer, Please include a sample file in the initial post.

Sort Pivot on double-clicking column header

Vivek D

Member
I am trying to implement functionality such that when a user double click the header in a pivot table, it will sort the pivot table by value in that header. The sorting order should toggle between ascending and descending on each double-click.

I have the code to sort it by one of the columns but can't figure out how to make it generic so that the code knows which column was clicked and sort accordingly.
Specifically, need to know how to determine PivotLine Item number (marked in Red below) based on what was clicked. Hopefully and easy way instead of doing math between column numbers and determining the item number.

Code:
pvtTbl.PivotFields("Category A").AutoSort xlAscending _
        , "Sum of Cash", pvtTbl.PivotColumnAxis.PivotLines(4), 1
 

Attachments

  • Sort Pivot.xlsm
    29.2 KB · Views: 7
So you need some way to identify PivotLines().

1 = China
2 = India
3 = Russia
4 = USA

Alternately you can use PivotItems().DataRange
For example to select data field for China column
Code:
ActiveSheet.PivotTables("Pivot").PivotFields("Category C").PivotItems("China").DataRange
 
Here's the method using PivotItems().DataRange.Select

Code:
Sub SortPivot(columnToSort As Range)
   
    Dim pvtTbl As PivotTable
    Dim sString As String
    Set pvtTbl = ActiveSheet.PivotTables(columnToSort.PivotTable.Name)
    sString = "" & columnToSort & ""
    ActiveSheet.PivotTables("Pivot").PivotFields("Category C").PivotItems(sString).DataRange.Select
    Selection.Sort Order1:=xlAscending
End Sub
 
Back
Top