简体   繁体   中英

Sort Excel Pivot Items based on Date

Edit: Solved it!! Can't put up solution just yet.

I have a pivottable with a "dates" rowfield. I need a VBA code that sorts from oldest dates to the newest.

I need the dates to be AUS format, ie. dd/mm/yyyy or d mmm yyyy or similar. This is when Excel does not order them correctly.

So let's say that pivotfield "Dates" has the following pivot items:

01 Jan 2012
30 Apr 2012
(blank)
03 Feb 2013
14 Feb 2012
22 Nov 2012

The correct order would be:

01 Jan 2012
14 Feb 2012
30 Apr 2012
22 Nov 2012
03 Feb 2013
(blank)

I think I am getting closer but still no luck.

Dim pi As PivotItem
Dim pfd As PivotField
Dim pt As PivotTable

Set pfd = pt.PivotFields("Snapshot Date")

For Each pi In pfd.PivotItems
pi = CDate(pi) 'converts to US date for sorting 
Next pi

pfd.AutoSort _
xlAscending, "Snapshot Date"

For Each pi In pfd.PivotItems
pi = Format(pi, "d mmm yyyy") 'converts to AUS
Next pi

Thanks for your help. Ramify

I think you don't have to create a macro for that. Select your dates, right click->cell format->date->pick the format you want for your dates.

Then to sort, select all your lines you want to sort, go to data/sort, select the column with your dates and a sorting order (ascending/descending) and click ok.

Your dates should be sorted ;)

EDIT: as you're using a macro, try something like that

Set pfd = pt.PivotFields("Snapshot Date")
pfd.Sort Key1:=Range("A1"), Order1:=xlDescending, Header:=xlYes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM