excel - 升序/降序vba excel

标签 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

最佳答案

这段代码对我有用:

  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

希望这能解决问题!!!

关于excel - 升序/降序vba excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14858800/

相关文章:

java - 如何将 Excel 中的图表另存为图像/PDF?

vba - 跟踪更改时,出现VBA编译错误

vba - 如何使类变量在VBA中的模块之间持久存在

ms-access - Access VBA : Changing record source of subform

excel - CRTL + Tilde 然后将 "exploded"公式复制粘贴到 excel 中

vba - 循环 VBA 宏以打开文件夹中的文件、导入行,然后使用相对路径移动到另一个文件夹

excel - 使用VBA中的find方法

vba - Excel VBA 错误 438 "Object doesn' t 支持此属性或方法”

vba - 将文本添加到文本框 Excel VBA

excel - 如何使用 VBA 删除 Module1?