2

我有一个关于如何在通过用户表单将信息提交到表中时自动对信息进行排序的问题。

我尝试了以下代码,但出现错误。因为我是 Excel 编码的新手,所以我不知道如何进行这项工作:

Dim LR As Integer
LR = Range("A1:E1").End(xlUp).Row
Application.EnableEvents = False
Range("A1:BB" & LR).Sort Key1:=Range("A1"), Order1:=xlDescending, _
Header:=xlGuess, OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom
Application.EnableEvents = True

标题图片

标题信息

用户窗体图像

用户窗体

用户窗体本身工作得很好。我想按日期列中的降序排序。

4

1 回答 1

0
  1. 限定您要使用的确切工作表和范围。
  2. 每次清除排序并重新应用排序。
  3. 在设置排序范围之前获取最后使用的数据范围。(您设置的方式LR将始终是第一行。)

像这样:

Application.EnableEvents = False

Dim ws As Worksheet
Set ws = Sheets("Sheet1") 'change as needed

With ws

    Dim LR As Long, rng As Range

    LR = .Range("A" & .Rows.Count).End(xlUp).Row
    Set rng = .Range("A1:BB" & LR)

    With ws.Sort

        With .SortFields
            .Clear
            .Add Key:=ws.Range("A2:A" & LR), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
        End With

        .SetRange rng
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply

    End With

End With


Application.EnableEvents = True
于 2015-11-30T21:44:05.207 回答