自定义自动排序宏Excel

时间:2013-10-24 22:27:29

标签: excel vba excel-vba

我想自定义下面的宏。我希望宏做的是按照下面的列表自动排序。关于如何做到这一点的任何建议?

谢谢。

代码:

Private Sub Worksheet_Change(ByVal Target As Range)
    On Error Resume Next
    If Not Intersect(Target, Range("A:A")) Is Nothing Then
        Range("A7").Sort Key1:=Range("A8:A18"), _
          Order1:=xlDescending, Header:=xlYes, _
          MatchCase:=False, _
          Orientation:=xlTopToBottom

End If
End Sub

首选排序结构:

  • 最佳选择
  • 谨慎使用
  • 不推荐

1 个答案:

答案 0 :(得分:0)

编辑:

由于您被迫在排序中使用这些值,因此下面的代码应执行自定义排序(只需将dataCell值更改为数据所在的位置):

Sub sortData()

Dim sh1 As Worksheet
Dim rSort As Range
Dim rKey As Range
Dim customSort(1 To 3) As String
Set sh1 = ActiveWorkbook.Worksheets("Sheet1")

dataCell = "A7" ' Change this to the top left-hand cell in your dataset

Set rSort = sh1.Range(dataCell).CurrentRegion
Set rKey = sh1.Range(dataCell)

customSort(1) = "Best Choice"
customSort(2) = "Use Caution"
customSort(3) = "Not Recommended"

Application.AddCustomList ListArray:=customSort
rSort.Sort Key1:=rKey, Order1:=xlAscending, Header:=xlGuess, _
OrderCustom:=Application.CustomListCount + 1, MatchCase:=False, _
Orientation:=xlTopToBottom, DataOption1:=xlSortNormal

End Sub