Excel 2010 Worksheet_Deactivate()自动排序

时间:2014-05-01 16:29:06

标签: excel vba sorting

我是VBA的菜鸟。每当我离开那个页面时,我都试图让页面自动排序。该页面有六种针对各种列的手动排序,但需要在第一列为alpha,以便在另一页上进行查找。因此,当用户手动对另一个字段进行排序时,我希望它在离开页面时恢复到所需的列排序。我已经尝试过六种不同的宏,我已经找到了它们并对它们进行了一些编辑,但它们似乎都没有做任何事情。这是我最近的尝试:

Private Sub Worksheet_Deactivate()

    With Me.Range("B6:K604").CurrentRegion
        .Sort Key1:=Range("B6:B604"), Order1:=xlAscending, _
        Header:=xlNo, OrderCustom:=1, MatchCase:=False, _
        Orientation:=xlTopToBottom, DataOption1:=xlSortNormal
    End With

End Sub

2 个答案:

答案 0 :(得分:1)

试试这个:

Private Sub Worksheet_Deactivate()
Dim sortkey As Range, sortrng As Range

With me
    Set sortkey = .Range("B6:B604")
    Set sortrng = .Range("B6:K604")
End With

me.Sort.SortFields.Clear
me.Sort.SortFields.Add Key:=sortkey, SortOn:=xlSortOnValues, _
    Order:=xlDescending, DataOption:=xlSortNormal
With me.Sort
    .SetRange sortrng
    .Header = xlNo
    .MatchCase = False
    .Orientation = xlSortColumns
    .SortMethod = xlPinYin
    .Apply
End With

End Sub

好的,这是经过试验和测试 关键是首先清除现有的过滤器。

答案 1 :(得分:0)

参加另一项活动:

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Sheets("Sheet1").Activate
With Sheets("Sheet1").Range("B2:C9").CurrentRegion
    .Sort Key1:=Range("B6:B604"), Order1:=xlAscending, _
    Header:=xlNo, OrderCustom:=1, MatchCase:=False, _
    Orientation:=xlTopToBottom, DataOption1:=xlSortNormal
End With
End Sub

激活工作表,排序并保存......