0

I recorded this macro to sort a pivot table.

However, the pivot table is dynamic, and this macro only works if the pivot table ends in the correct column (k).

Is there a way to make it so the macro affects the last column with data in it?

On Error GoTo ErrorHandler
ErrorHandler:
 Resume Next
 Range("K4").Select
    ActiveSheet.PivotTables("InventoryPivotTable").PivotFields("Products"). _
        AutoSort xlAscending, "FBM ", ActiveSheet.PivotTables("InventoryPivotTable"). _
        PivotColumnAxis.PivotLines(8), 1
        
  ActiveWorkbook.ShowPivotTableFieldList = False
  Call highlightNegativeNumbersFBM

1 Answer 1

1

You probably don't even need the line that says "Select"

You also don't need to know that it is sorting by column k, it's really sorting by the 8th Pivot line which happens to be in K.

So if I were rewriting this line

    ActiveSheet.PivotTables("InventoryPivotTable").PivotFields("Products").       AutoSort xlAscending, "FBM ", ActiveSheet.PivotTables("InventoryPivotTable").        PivotColumnAxis.PivotLines(8), 1
dim lPivotTable as pivotTable
set lPivotTable = ActiveSheet.PivotTables("InventoryPivotTable") 

call LPivotTable.PivotFields("Products").AutoSort(xlAscending, "FBM ", lPivotTable.PivotColumnAxis.PivotLines(lPivotTable.PivotColumnAxis.PivotLines.Count), 1)

Besides shortening it, using the variable, I replaced the 8 with lPivotTable.PivotColumnAxis.PivotLines.Count which should equal 8 until you add or remove items

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.