0

I need to use a sort function in an personal.xlsb file where I can only use active sheet and workbook statements. By use of a dynamic range to avoid hard coding. Reason is that the content of the active sheet varies.

I checked this website and tried various combinations and they all run into issues. This code is the only code I tried that did not run into a global variable error.

''''Start Function Sort

Function PTSort()

ActiveSheet.Range("A1").Select
Columns("A:A").EntireColumn.AutoFit

Dim MyLastRow As Long
    MyLastRow = Cells(Cells.Rows.Count, "A").End(xlUp).Row
Dim MySortRange As String
Let MySortRange = "A1:A" & MyLastRow

Range(MySortRange).Select
ActiveWorkbook.Worksheets("MySheet").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("MySheet").Sort.SortFields.Add 
Key:=Range(MySortRange) _
    , SortOn:=xlSortOnValues, Order:=xlAscending, 
DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("MySheet").Sort. _
    SortFields.Add _
    SetRange = Key:=Range(MySortRange), _
    Header = xlYes, _
    MatchCase = False, _
    Orientation = xlTopToBottom, _
    SortMethod = xlPinYin, _
    Apply
End With

Exit Function
Application.ScreenUpdating = True
End Function

''''End of function Sort

I would like to call a some code which also has an sort function. All code works only the sort function keep failing. The idea is to specify a dynamic range bacause content varies per sheet. Need to sort column A:A and I want to set the found cells in an variable and call it as a range.

Pᴇʜ
  • 56,719
  • 10
  • 49
  • 73
vinmeg
  • 41
  • 5

0 Answers0