sort ascending/descending vba excel

后端 未结 3 1245
悲&欢浪女
悲&欢浪女 2020-12-04 01:22

I want to sort a column (it\'s a flagcolumn with Y/N). It should Toggle between ascending / descending on every click.

my code is not working..I am new to VBA. Any h

相关标签:
3条回答
  • 2020-12-04 01:39

    This will be easier if you declare a range variable ("rng" in the example below). This code should fix it.

    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
    
    0 讨论(0)
  • 2020-12-04 01:40

    To sort ascending and descending with 2 keys

    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
    
    0 讨论(0)
  • 2020-12-04 01:47

    This code worked for me:

      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
    

    Hope this does the trick!!!

    0 讨论(0)
提交回复
热议问题