sort ascending/descending vba excel

后端 未结 3 1247
悲&欢浪女
悲&欢浪女 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: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
    

提交回复
热议问题