我已将以下宏分配给电子表格的第一列,以按升序和降序对信息进行排序。该宏被分配给命令按钮并起作用。
If CommandButton1.Caption = "Click to Sort Ascending" Then
'Sort ascending...
ActiveWorkbook.Worksheets("daily data drop").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("daily data drop").Sort.SortFields.Add Key:=Range("A2:A308"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("daily data drop").Sort
.SetRange Range("A2:Z308")
.Header = xlGuess
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
CommandButton1.Caption = "Click to Sort Decending"
Else
'sort decending
ActiveWorkbook.Worksheets("daily data drop").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("daily data drop").Sort.SortFields.Add Key:=Range("A2:A308") _
, SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("daily data drop").Sort
.SetRange Range("A1:Z308")
.Header = xlGuess
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
CommandButton1.Caption = "Click to Sort Ascending"
End Sub
我希望每列的所有顶部标题都有一个按钮,按照上面的宏进行升序和降序排序,以保持行数据匹配。任何人都可以帮我这个或者有一个可能有用的模板。
答案 0 :(得分:1)
在每列上放置一个按钮并不是一个好主意。我会建议一种根本不需要按钮的方法。此外,您应始终避免复制代码的大部分内容,其中只有一个或两个语句根据某些参数而不同。你应该总是尝试"分解"您的代码并尽可能缩短它,这使它更具可读性和可维护性。
实现目标的一种可能方式是用户"双击"在标题单元格上,并按照单击的列排序数据。每次排序后,排序顺序都会颠倒过来。
您可以通过将以下处理程序添加到工作表"daily data drop"
的代码模块中来实现:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Static descending As Boolean
If Target.Row <> 1 Then Exit Sub
Cancel = True
Me.UsedRange.Sort Target, IIf(descending, xlDescending, xlAscending), Header:=xlYes
descending = Not descending
End Sub