[英]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 我正在使用它作为更大的VBA子的一部分,但我只是发布下面的相关代码
I want to sort a range (by A to Z) on a separate Workbook. 我想在单独的工作簿上对范围(A到Z)进行排序。 The range is "A5:M600" and the worksheet is "Leaders". 范围是“A5:M600”,工作表是“领导者”。 This is stored on the Workbook declared as 'wb2'. 它存储在声明为'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. 尝试从远离.Activate
和.Select
的方式引导你的代码的目标。
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. 这将把A列排序为主键,然后将列C排序为辅助键。 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. 您可以添加第三个键(例如Key3:=.Columns(14), Order3:=xlAscending
用于列N上升)但它最多有三个键。 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. 请参阅如何避免在Excel VBA宏中使用Select以获取更多方法, 以避免依赖select和activate来实现目标。
Hm, it may be that you should be explicit with your ranges. 嗯,可能你应该明确你的范围。 Try this for the With statement: 尝试使用With语句:
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. 我想(希望!)这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.