简体   繁体   中英

Using VBA to control the order of elements in an Excel Pivot Table Field List

I am trying to move a Values data field in a Pivot Table from 1st position to 7th position. My current code is taking the last entry in the last position of the Values data field list and putting it into the 7th slot instead. How can I alter my code to fit my needs?

Field List - Values

Sub Macro7()

   With Sheets("Sheet1").PivotTables("PivotTable1").PivotFields("Sunday")
    .Orientation = xlDataField
    .Position = 7
End With

End Sub
This will do the trick,
just change the  .**Orientation** 

Sub Macro7()

   With Sheets("Sheet1").PivotTables("PivotTable1").PivotFields("Sunday")
    .Orientation = xlRowField
    .Position = 7
  End With

End Sub

This is what I came up with. It deletes all field within the Values section of the Field List. It then adds them back in the correct order. A bit slow, but I haven't found a better way of doing it yet.

 Worksheets("Sheet1").PivotTables("PivotTable1").DataPivotField.Orientation = xlHidden
    Worksheets("Sheet1").PivotTables("PivotTable1").AddDataField Worksheets("Sheet1").PivotTables( _
        "PivotTable1").PivotFields("Mon"), "Monday", xlCount
    Worksheets("Sheet1").PivotTables("PivotTable1").AddDataField Worksheets("Sheet1").PivotTables( _
        "PivotTable1").PivotFields("Tue"), "Tuesday", xlCount
    Worksheets("Sheet1").PivotTables("PivotTable1").AddDataField Worksheets("Sheet1").PivotTables( _
        "PivotTable1").PivotFields("Wed"), "Wednesday", xlCount
    Worksheets("Sheet1").PivotTables("PivotTable1").AddDataField Worksheets("Sheet1").PivotTables( _
        "PivotTable1").PivotFields("Thu"), "Thursday", xlCount
    Worksheets("Sheet1").PivotTables("PivotTable1").AddDataField Worksheets("Sheet1").PivotTables( _
        "PivotTable1").PivotFields("Fri"), "Friday", xlCount
    Worksheets("Sheet1").PivotTables("PivotTable1").AddDataField Worksheets("Sheet1").PivotTables( _
        "PivotTable1").PivotFields("Sat"), "Saturday", xlCount
    Worksheets("Sheet1").PivotTables("PivotTable1").AddDataField Worksheets("Sheet1").PivotTables( _
        "PivotTable1").PivotFields("Sun"), "Sunday", xlCount
    Worksheets("Sheet1").PivotTables("PivotTable1").AddDataField Worksheets("Sheet1").PivotTables( _
        "PivotTable1").PivotFields("Total Hours"), "Total", xlCount

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