在下面的代码中,我在DepName列上对名为DepList的表进行排序。
Sub SortDepNameAZ()
On Error Resume Next
ActiveWorkbook.Worksheets("Department List").ListObjects("DepList").Sort. _
SortFields.Clear
ActiveWorkbook.Worksheets("Department List").ListObjects("DepList").Sort. _
SortFields.Add Key:=Range("DepList[[#All],[DepName]]"), SortOn:= _
xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Department List").ListObjects("DepList").Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
我想让它更通用,所以我可以使用它作为一个函数,使用定义的范围和名称而不是特定的名称。
我已尝试使用以下内容,但我无法使语法有效:
Sub SortDepNamesAZ(lo1 As ListObject, dn1 as Variant)
On Error Resume Next
Set lo1 = Application.ActiveWorkbook.ActiveSheet.ListObject(1)
Dim tabstr As String
tabstr = Application.ActiveWorkbook.ActiveSheet.ListObject(1).Name
lo1.Sort.SortFields.Clear
lo1.Sort.SortFields.Add Key:=Range(tabstr[[#All],[dn1]]), SortOn:= _
xlSortOnValues, Order:=xlAscending 'I think this line is probably wrong??
With lo1.Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
任何帮助都表示赞赏,即使只有几个指针,因为我知道代码可能会在许多级别上得到改进。
由于
答案 0 :(得分:0)
功能:
Sub SortTableByHeader(ShtN As String, tabN As String, hed1 As Variant)
Dim hed2 As Range, hed3 As Integer
Set hed2 = Range(tabN).Rows(0)
hed3 = Application.Match(hed1, hed2, 0)
Range(tabN).Sort Key1:=Range(tabN).Cells(1, hed3), Header:=xlYes
End Sub
调用该函数:
Sub SortDepartmentName()
Dim ShtN As String, objName As String, myColHead As Variant
ShtN = Sheets("Department List").Name
objName = Sheets("Department List").ListObjects(1).Name
myColHead = "DepName"
SortTableByHeader ShtN, objName, myColHead
End Sub