【问题标题】:Custom sort with 3 keys使用 3 个键进行自定义排序
【发布时间】:2013-10-15 07:36:19
【问题描述】:

我有一个范围,我正在尝试使用 3 个键自定义排序。 我正在尝试从工作表上的两个不同列构建两个字符串数组,并使用它们创建两个可以排序的自定义列表 - 第三个键只是通过标准键排序。

但是,我无法按照客户列表的确切顺序对范围进行排序,我相信它只是升序排序。

下面是我的代码:

Sub SortIntoTeams()
Dim LastRow As Long, LastColumn As Long, FormattedRange As Range
LastRow = Sheets(1).Range("B65536").End(xlUp).Row
LastColumn = Sheets(1).Cells(1, Columns.Count).End(xlToLeft).Column
Set FormattedRange = Sheets(1).Range(Cells(8, 1), Cells(LastRow, LastColumn))

Dim SortKey1 As Range, SortKey2 As Range, SortKey3 As Range
Set SortKey1 = Sheets(1).Cells(7, 1)
Set SortKey2 = Sheets(1).Cells(7, 10)
Set SortKey3 = Sheets(1).Cells(7, 3)

Dim sCustomList1() As String, sCustomList2() As String
Dim x As Long, i As Long
ReDim sCustomList1(1 To Sheets(1).Range("A65536").End(xlUp).Row)
ReDim sCustomList2(1 To Sheets(1).Range("E65536").End(xlUp).Row)

For x = 1 To Sheets(1).Range("A65536").End(xlUp).Row
    sCustomList1(x) = Sheets(2).Cells(x, 1)
Next x
For i = 1 To Sheets(1).Range("E65536").End(xlUp).Row
    sCustomList2(i) = Sheets(2).Cells(i, 5)
Next i

Application.AddCustomList ListArray:=sCustomList1
Application.AddCustomList ListArray:=sCustomList2

Sheets(1).Sort.SortFields.Clear
FormattedRange.Sort Key1:=SortKey1, Order1:=xlAscending, Key2:=SortKey2, Order2:=xlAscending, Key3:=SortKey3, Order3:=xlAscending, Header:=xlGuess, _
    OrderCustom:=Application.CustomListCount + 1, MatchCase:=False, _
    Orientation:=xlTopToBottom, DataOption1:=xlSortNormal

Application.DeleteCustomList Application.CustomListCount

End Sub

【问题讨论】:

    标签: vba excel


    【解决方案1】:

    我注意到有两件事在这里可能会有所帮助。

    重写获得要使用的最后一行的部分,如下所示: Sheets(1).Cells(rows.count,1).end(xlup).row ' 这将用于 A 列。 Sheets(1).cells(rows.count,2).end(xlup).row ' 这将用于 B 列。

    您将使用 rows.count,5 来表示 E 列中的内容。

    另外,您似乎需要指明一种排序方法,例如:sortmethod:=xlpinyin

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-29
      • 2014-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 2018-08-26
      相关资源
      最近更新 更多