简体   繁体   中英

Sorting Data in Workbook2 from Workbook1

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 Files\2015\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

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 (eg 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.

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.

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