Please dont close this question. I havent got a solution and its not a duplicate question, please understand the query.
I have a pivot table that has multiple columns, I want to dynamically rearrange the columns .
Sample pivot column header
| Row Label | 1 day | 10 days | 11 days | 13 days | 17 days | 2 days | 21 days | 3 days |
|---|
I want to rearrange this in ascending order. like this
| Row Label | 1 day | 2 days | 3 days | 10 days | 11 days | 13 days | 17 days | 21 days |
|---|
Points to note:
- the pivot table is made dynamically
- No assurity on column names remaining the same, it can change according to data set.
- Data set cant be changed, cant edit it to 01 days,02 days etc.
Additionally, if this was a normal table/column we would have gone with a header sorting function (Code given below), can something of the same be applied here??
Specifically, storing values in an array, and using that to sort the pivot table column header??
Function Reorder_Columns()
Dim ColumnOrder As Variant, ndx As Integer, Found As Range, counter As Integer, ws As Worksheet
Set ws = ActiveWorkbook.Sheets("Sheet1")
ws.Activate
ColumnOrder = Array("Item 1", "Item 2", "Item 3", "Item 4")
counter = 1
Application.ScreenUpdating = False
For ndx = LBound(ColumnOrder) To UBound(ColumnOrder)
Set Found = Rows("1:1").Find(ColumnOrder(ndx), LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False)
If Not Found Is Nothing Then
If Found.Column <> counter Then
Found.EntireColumn.Cut
Columns(counter).Insert Shift:=xlToRight
Application.CutCopyMode = False
End If
counter = counter + 1
End If
Next ndx
Application.ScreenUpdating = True
EDIT Answers given by Both Raymond Wu and Tim Williams are perfect for this with difference in time for each being .04 seconds.
ActiveSheet.PivotTables("PivotTable1").PivotFields("Column Labels").AutoSort xlAscending, "Column Labels".. Also, the code in the question doesn't look like for Pivot