Home » excel » excel – Sorting Data in Workbook2 from Workbook1

excel – Sorting Data in Workbook2 from Workbook1

Posted by: admin April 23, 2020 Leave a comment

Questions:

I’m not sure why the code below isn’t working. I’m using this as a part of a larger VBA sub, but I’ll just post the relevant code below

I want to sort a range (by A to Z) on a separate Workbook. The range is “A5:M600” and the worksheet is “Leaders”. This is stored on the Workbook declared as ‘wb2’.

The code below will get as far as opening the file where I want to execute the sort, select the range I want to sort, but it won’t actually sort the selection.

Any ideas?

Sub SortWB2()
Dim wb2 As Workbook
Dim RetFilePath

'~~> Get the file path
RetFilePath = "T:\Purchasing\ADVENTURE RMS\Data Files15\Data.xlsx"

'if file path is not found, then exit the sub below
If RetFilePath = False Then Exit Sub

'set wb2 to open the file
Set wb2 = Workbooks.Open(RetFilePath)


With wb2.Worksheets("Leaders").Sort
    .SetRange Range("A5:M600")
    .Header = xlNo
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

Application.DisplayAlerts = False
wb2.Close SaveChanges:=True
Application.DisplayAlerts = True


Set wb2 = Nothing

End Sub
How to&Answers:

Try to stay away from .Activate and .Select as ways to direct the target of your code.

Set wb2 = Workbooks.Open(RetFilePath)

With wb2.Worksheets("Leaders").Range("A5:M600")
    .Cells.Sort Key1:=.Columns(1), Order1:=xlAscending, _
                Key2:=.Columns(3), Order2:=xlDescending, _
                Orientation:=xlTopToBottom, Header:=xlNo
End With

That will sort on column A as the primary key then column C as the secondary key. You can remove the secondary key if it is not needed. You can add a third key (e.g. Key3:=.Columns(14), Order3:=xlAscending for column N ascending) but it has a maximum of three keys. You can double up the command if you require more.

See How to avoid using Select in Excel VBA macros for more methods on getting away from relying on select and activate to accomplish your goals.

Answer:

Hm, it may be that you should be explicit with your ranges. Try this for the With statement:

With wb2.Worksheets("Leaders").Sort
    .SetRange wb2.worksheets("Leaders").Range("A5:M600")
    .Header = xlNo
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

I think (hope!) that does it.