排序升序/降序vba excel

时间:2013-02-13 16:57:53

标签: excel vba

我想对列进行排序(它是带有Y / N的标志列)。它应该在每次点击时在上升/下降之间切换。

我的代码无效。我是VBA的新手。请帮忙。

Private Sub CommandButton1_Click()

   Dim xlSort As XlSortOrder 
   Dim LastRow As Long 

   With ActiveSheet

       LastRow = .Cells(.Rows.Count, "E").End(xlUp).Row End With

       If (Range("E2").Value > Range("E" & CStr(LastRow))) Then
           xlSort = xlAscending
       Else
           xlSort = xlDescending
       End If

       .Sort Key1:=Range("E2"), Order1:=xlSort, Header:=xlNo, _
          OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
          DataOption1:=xlSortNormal    


    ActiveWorkbook.Save  

End Sub

3 个答案:

答案 0 :(得分:6)

此代码对我有用:

  Private Sub CommandButton1_Click()

     Dim xlSort As XlSortOrder
     Dim LastRow As Long

     With ActiveSheet

         LastRow = .Cells(.Rows.Count, "E").End(xlUp).Row

         If (.Range("E2").Value > .Range("E" & CStr(LastRow))) Then
             xlSort = xlAscending
         Else
             xlSort = xlDescending
         End If

         .Range("E2:E" & LastRow).Sort Key1:=.Range("E2"), Order1:=xlSort, Header:=xlNo, _
            OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
            DataOption1:=xlSortNormal


     End With
     ActiveWorkbook.Save

  End Sub

希望这可以解决问题!!!

答案 1 :(得分:0)

如果声明一个范围变量(下例中的“rng”),这将更容易。这段代码应该修复它。

Private Sub CommandButton1_Click()

Dim xlSort As XlSortOrder
Dim LastRow As Long
Dim rng As Range

With ActiveSheet
   LastRow = .Cells(.Rows.Count, "E").End(xlUp).Row
    Set rng = Range("E2").Resize(LastRow, 1)

    With rng
        If (.Cells(1).Value > .Cells(LastRow - 1).Value) Then
           xlSort = xlAscending
        Else
           xlSort = xlDescending
        End If

        .Sort Key1:=.Cells(1), Order1:=xlSort, Header:=xlNo, _
            OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
            DataOption1:=xlSortNormal
    End With
 End With

 ActiveWorkbook.Save

End Sub

答案 2 :(得分:-1)

使用2个键进行升序和降序排序

Sub Button1_Click()

     Dim xlSort As XlSortOrder
     Dim LastRow As Long

     With ActiveSheet

         LastRow = .Cells(.Rows.Count, "E").End(xlUp).Row

         If (.Range("E2").Value > .Range("E" & CStr(LastRow))) Then
             xlSort = xlAscending
         Else
             xlSort = xlDescending
         End If

         .Range("E2:E" & LastRow).Sort Key1:=.Range("E2"), Order1:=xlSort, Header:=xlNo, _
            OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
            DataOption1:=xlSortNormal

     End With
     ActiveWorkbook.Save

End Sub