VBA按列名称或是按表格标题给EXCEL表格做排序

VBA给EXCEL表格做排序

按列名称或是按标题给表格排序

在VBA编程时,经常会对表格内容进行排序,为了方便对不同需求下的内容排序,编制了下面这个函数,此函数可以根据给定的列名称(A、B、C……),或是列的标题(“序号”、“姓名”、“年龄”……)进行排序,并且可以指定是升序或是降序。
本函数可以设置需要排序的开始行(标题行),默认为有标题行,默认为所有的列全部参与排序,表格的全部列数一般不超过26列。
本函数暂不支持对多列同时排序,有兴趣的可以对col_Name进行解析,并逐个添加排序列:Ws_Rec.Sort.SortFields.Add,可以实现多列排序。

引用方法:
Sort_Ws ActiveWorkbook.ActiveSheet, “A”, , xlDescending

Function Sort_Ws(Ws_Rec As Worksheet, Col_Name, Optional Row As Integer = 1, Optional Sort As Integer = xlAscending)
'排序 按照名称
Dim Last_Row As Integer
Dim Last_Col As Integer
On Error GoTo err
Sort_Ws = True
Last_Row = Ws_Rec.UsedRange.Rows(Ws_Rec.UsedRange.Rows.Count).Row
Last_Col = Ws_Rec.UsedRange.Columns(Ws_Rec.UsedRange.Columns.Count).Column
If Sort <> xlAscending Then Sort = xlDescending
If Not Col_Name Like "[a-zA-Z]" Then
    Set Col_Name = Ws_Rec.Range(Row & ":" & Row).Find(Col_Name, lookat:=xlWhole)
    If Not Col_Name Is Nothing Then Col_Name = Col_Name.Column
    Col_Name = Chr(64 + Col_Name)
End If
'Ws_Rec.Columns(Col_Name & ":" & Col_Name).Select
Ws_Rec.Sort.SortFields.Clear
Ws_Rec.Sort.SortFields.Add Key:=Range(Col_Name & Row) _
    , SortOn:=xlSortOnValues, Order:=Sort, DataOption:=xlSortNormal
With Ws_Rec.Sort
    .SetRange Range("A" & Row & ":" & Chr(64 + Last_Col) & Last_Row)
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With
Exit Function
err:
Sort_Ws = err.Number & "_" & err.Description
End Function

猜你喜欢

转载自blog.csdn.net/w_dexu/article/details/107050809
今日推荐