Excel VBA Pivot Table Sorting: A Complete Guide
In this article
Sorting a Pivot Table via VBA is achieved by accessing the PivotField object and applying the AutoSort method. This allows you to automate the organization of your data—such as sorting sales from highest to lowest—without having to manually right-click and sort every time your data refreshes. To do this, you need a functioning Pivot Table already created in your workbook and a basic understanding of how to access the Visual Basic Editor.
What You'll Need
- Microsoft Excel installed on Windows or macOS.
- A workbook containing a Pivot Table.
- The Developer tab enabled in the Excel Ribbon (if not visible, right-click the ribbon, select Customize the Ribbon, and check the Developer box).
- Knowledge of the exact names of your Pivot Fields (the column headers from your source data).
Step-by-Step
- Open the Visual Basic Editor: Press
Alt + F11on your keyboard. This opens the VBA window where you will write your automation script. - Insert a New Module: In the top menu, go to Insert > Module. This creates a blank space for your code, ensuring it stays separate from the sheet-specific code.
- Define Your Variables: Start your macro by declaring the objects you will be manipulating. You need a variable for the Workbook, the Worksheet, the Pivot Table, and the Pivot Field. Using
Dimstatements prevents errors and improves code performance. For example:Dim pt As PivotTableDim pf As PivotField - Set the Pivot Table Reference: Tell VBA which Pivot Table you are targeting. If you have only one table on a specific sheet, you can reference it by name or index.
Set pt = ThisWorkbook.Worksheets("Sheet1").PivotTables("PivotTable1")
Ensure the sheet name and table name match exactly what is seen in the PivotTable Analyze tab in Excel. - Set the Pivot Field Reference: Identify the specific field you want to sort. If you want to sort the row labels based on a value, you must reference the field that contains those labels.
Set pf = pt.PivotFields("Customer Name") - Apply the AutoSort Method: Use the
AutoSortmethod to define the order. This method requires two arguments: the order (Ascending or Descending) and the field that determines the sort value.
To sort the "Customer Name" field based on the "Sum of Sales" value in descending order, use:pf.AutoSort xlDescending, "Sum of Sales"
Note that the second argument must be the exact name of the data field as it appears in the Pivot Table values area. - Run the Macro: Close the VBA editor and return to Excel. Press
Alt + F8, select your macro name, and click Run. Your Pivot Table should now be sorted automatically.
Common Mistakes
One of the most frequent errors is using the wrong field name in the AutoSort method. Users often use the name of the original column from the source data (e.g., "Sales") instead of the name as it appears in the Pivot Table (e.g., "Sum of Sales"). VBA is literal; if the Pivot Table renamed the field during the aggregation process, you must use that new name.
Another common mistake is attempting to sort a field that is not currently in the Pivot Table layout. If you try to reference a PivotField that is sitting in the field list but not actually placed in the Rows or Columns area, VBA will trigger a "Run-time error 1004". Always ensure the field is active in the table before running the sort command.
Many users also forget to refresh the Pivot Table before sorting. If the source data has changed, the sort order might be based on outdated values. It is best practice to add pt.RefreshTable at the beginning of your code to ensure the sort is applied to the most current data.
Tips
To make your code more flexible, avoid hard-coding sheet names. Instead, use ActiveSheet if the macro will always be run while the user is looking at the table. This allows the same macro to work across different workbooks as long as the Pivot Table name remains consistent.
If you are sorting by a date field, be aware of how Excel handles grouping. If your dates are grouped by Month or Year, you must sort the grouped field (e.g., "Months") rather than the original date field. VBA treats grouped fields as distinct entities.
For those creating professional dashboards, consider placing the sorting code within the Worksheet_PivotTableUpdate event. This is a special trigger that runs your VBA code automatically every time the Pivot Table is filtered or refreshed, ensuring the sort order is maintained without manual intervention.
Troubleshooting
If you encounter a "Subscript out of range" error, it almost always means VBA cannot find the worksheet or the Pivot Table name you provided. Double-check the spelling and capitalization. Go to the PivotTable Analyze tab and check the "PivotTable Name" box on the far left to verify the exact string.
If the code runs without error but the table does not sort, check if you have manual sorting applied. Sometimes, manual drag-and-drop sorting overrides programmatic sorting. Try clearing the sort manually first, or ensure you are using xlDescending or xlAscending correctly.
In cases where the AutoSort method fails due to complex data types, try converting the field to a standard format. If your values are stored as text instead of numbers, the sort will be alphabetical (1, 10, 2) rather than numerical (1, 2, 10). Ensure your source data is formatted as numbers before creating the Pivot Table.
If your VBA editor freezes, check if you have an infinite loop or if the workbook is protected. VBA cannot modify the structure or sorting of a Pivot Table if the worksheet is protected. Use ActiveSheet.Unprotect "YourPassword" at the start of your code and ActiveSheet.Protect "YourPassword" at the end.
Frequently Asked Questions
Can I sort a Pivot Table by a field that isn't visible?
No, the field you are sorting must be part of the Pivot Table's current layout (either in Rows or Columns) for the AutoSort method to function correctly.
How do I sort in ascending order instead of descending?
Simply change the first argument of the AutoSort method from xlDescending to xlAscending. This will sort your data from A-Z or smallest to largest.
Does this work for both Windows and Mac versions of Excel?
Yes, the core PivotTable object model is consistent across both platforms, though the keyboard shortcuts to open the VBA editor may differ slightly on macOS.
Can I sort multiple fields at once using VBA?
Yes. You can repeat the Set pf = ... and pf.AutoSort ... sequence for each field you wish to sort. VBA will process these commands sequentially, applying the sorts in the order they appear in your code.
What happens if the data field name changes?
The code will break because it can no longer find the field name specified in the AutoSort argument. To prevent this, you can use a variable to hold the field name or use a loop to find the field by its index number instead of its name.