Excel VBA - 在多列上排序后取消选择范围

时间:2016-02-28 23:35:56

标签: excel vba sorting

我应用的代码如下,目的是对目标工作表范围进行排序A:H使用A,B,C,D作为该顺序的排序字段。代码实现了目的,但在代码执行后,屏幕结束于范围A:H被选中。我想清除选择。

如您所见,我尝试过使用

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`

1 个答案:

答案 0 :(得分:0)

Range.Sort method有一种更简洁的编码语法。但是,它一次仅限于三个。解决方案是首先按第四个键排序,然后按照您喜欢的顺序排序其余三个键。

SortFields键的父工作表默认为ActiveSheet property。传递给子过程的Worksheet Object没有明确的关系。

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。您不能在Range .Select上没有的单元格上使用ActiveSheet方法¹。

您可能会对以下Application.CutCopyMode property上的问与答感兴趣: Should I turn .CutCopyMode back on before exiting my sub procedure?

¹有关远离依赖选择和激活以实现目标的更多方法,请参阅How to avoid using Select in Excel VBA macros