Question

Here's an annoying issue. I've got a pivot table in an Excel spreadsheet which gets its data direct from a SQL server query.

The table has customers on the vertical axis, and dates on the horizontal access. Both need to be correctly sorted - i.e. customers as alphabetical top to bottom and dates in date order from left to right.

I've ensured that the data coming out of SQL is recognised by EXcel as a date field. You can sort the dates successfully using the manual A-Z function. But I need to do it automatically using VBA.

I had hoped (againt hope) that using two sorting parameters on the SQL query might do the trick:

sql = "SELECT * FROM myView ORDER BY Customer, Date"

Set pt = Worksheets("MyReport").PivotTables("MyPivot")
pt.PivotCache.CommandText = sql
pt.RefreshTable

But it doesn't.

I see than in Excel 2010 onwards there's a handy AutoSort function that should do what I need. But I'm stuck with 2007. Is there a way to sort my data in both dimensions?

Was it helpful?

Solution

Turns out there is an AutoSort feature in Excel 2007, but it belongs to the PivotFields object, rather than the pivot table itself.

Dim pt As PivotTable
Set pt = Worksheets("myWorksheet").PivotTables("myPivotTable")
pt.PivotFields("DATE").AutoSort xlAscending, "DATE"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top