Excel VBA – 在多列sorting后取消select范围

我所应用的代码如下所示,目的是按照A,B,C,D的sorting顺序对目标工作表范围A:H进行sorting。 代码达到目的,但在代码执行后,屏幕结束于范围A:H被选中。 我想清除select。

正如你看到我已经尝试使用

wsName.Range("A1").Select Application.CutCopyMode = False 

最后却没有像我预期的那样工作。

 Public Sub sSortColumn(wsName As Worksheet) With wsName.Sort With .SortFields .Clear .Add Key:=Range("A:A"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal .Add Key:=Range("B:B"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal .Add Key:=Range("C:C"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal .Add Key:=Range("D:D"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal End With .SetRange Range("A:H") .Header = xlYes .MatchCase = False .Orientation = xlTopToBottom .SortMethod = xlPinYin .Apply End With wsName.Sort.SortFields.Clear wsName.Range("A1").Select Application.CutCopyMode = False End Sub` 

Range.Sort方法有一个更简洁的编码语法。 但是,它一次只限于三个 。 解决办法是先按第四个键,然后按照你喜欢的顺序排列剩下的三个键。

SortFields Key的父工作表默认为ActiveSheet属性 。 与传递给子过程的工作表对象没有明确的关系。

 Sub main() 'wsName worried me so I'm making sure to 'pass in a correct worksheet object reference sSortColumn Worksheets("Sheet1") End Sub Public Sub sSortColumn(wsName As Worksheet) With wsName .Sort.SortFields.Clear '<~~reset the worksheet's .SortFields With .Cells(1, 1).CurrentRegion With .Resize(.Rows.Count, 8) '<~~ columns A:H originating at A1 .Cells.Sort Key1:=.Columns(4), Order1:=xlAscending, _ Orientation:=xlTopToBottom, Header:=xlYes '<~~sort the fourth column first .Cells.Sort Key1:=.Columns(1), Order1:=xlAscending, _ Key2:=.Columns(2), Order2:=xlAscending, _ Key3:=.Columns(3), Order3:=xlAscending, _ Orientation:=xlTopToBottom, Header:=xlYes '<~~sort the remaining three columns End With End With 'if you want to leave this worksheet's selection on A1 then 'first make sure that the worksheet is active and then 'select the cell .Activate .Range("A1").Select 'the above is really not necessary. The original selection on the worksheet was 'not changed End With End Sub 

同样不能保证传递给sSortColumn子过程的工作表对象是ActiveSheet。 您不能在不在ActiveSheet上的单元格上使用Range .Select方法1。


您可能会对以下Application.CutCopyMode属性的问题感兴趣: 在退出我的子过程之前是否应该再次打开.CutCopyMode?

¹ 请参阅如何避免使用在Excel VBAmacros中select更多的方法来摆脱依靠select和激活来实现您的目标。