Name

pivotfield.AutoSort(Order, Field)

Synopsis

Sort items in a pivot field

Argument

Settings

Order

Can be xlAscending, xlDescending, or xlManual (unsorted)

Field

The data field to sort

These settings are equivalent to the AutoSort Options on the PivotTable Field Advanced Options dialog box shown in Figure 13-20.

The following code sorts items in the ProductName field by sales rank:

Sub SortBySalesRank(  )
    Dim pt As PivotTable, pf As PivotField
    ' Uncomment this line to create pivot table.
    'CreatePivotTable
    ' Get pivot table.
    Set pt = Worksheets("BookSales").PivotTables(1)
    ' Get pivot field.
    Set pf = pt.PivotFields("ProductName")
    ' Sort items
    pf.AutoSort xlAscending, pt.DataFields(1).name
End Sub

Get Programming Excel with VBA and .NET now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.