我在A:C列中有一个表,在H列中,我以不同的顺序在B列上具有相同的值,如何基于H列对表进行排序?
Public Sub ReportSorting()
Dim sht As Worksheet
Dim LastRow As Long
Dim sRange As Range
Dim kRange As Variant
Dim nSort As Long
Set sht = ActiveSheet
LastRow = sht.Cells(sht.Rows.Count, "H").End(xlUp).Row
Set sRange = sht.Range("H2:H" & LastRow)
'Read values into array from range ActiveSheet
kRange = sRange.Value
Application.AddCustomList ListArray:=kRange
nSort = Application.CustomListCount
sht.Sort.SortFields.Clear
sht.Sort.SortFields.Add Key:=Range("B1:B" & LastRow), SortOn:=xlSortOnValues, Order:=xlAscending, CustomOrder:=nSort, DataOption:=xlSortNormal
With sht.Sort
.SetRange Range("A1:C" & LastRow)
.Header = xlYes
.MatchCase = True
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
我要
错误1004:对象“应用”的方法Add AddCustomList失败!
A:C表的名称为:Req,H在表外。
A B C ... H
PID ID Name SID
- 001 AAA 001
001 002 BBB 002
004 003 CCC 004
004 DDD 003
....
答案 0 :(得分:0)
答案 1 :(得分:0)
Application.AddCustomList方法只能容纳字符串,并且如上例所示,如果您尝试添加数字(范围),则会出错!
我尝试了一个简单的技巧,并添加了一个辅助列(来自ID),并且还在两个列的值(D和H)中添加了字符串“ abc”,如下所示:
A B C D ... H
PID ID Name HID SID
001 AAA abc001 abc001
001 002 BBB abc002 abc002
004 003 CCC abc003 abc004
004 DDD abc004 abc003
并排序D列:
sht.Sort.SortFields.Clear
sht.Sort.SortFields.Add Key:=Range("D1:D" & LastRow), SortOn:=xlSortOnValues, Order:=xlAscending, CustomOrder:=nSort, DataOption:=xlSortNormal
With sht.Sort
.SetRange Range("A1:D" & LastRow)
.Header = xlYes
.MatchCase = True
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
现在它正在工作;)