宏 - 按列名称进行多级排序

时间:2015-06-11 09:04:01

标签: excel vba sorting excel-vba

我从我放入excel的程序中下载了一组数据。从这里开始,我想将这些数据分为两个级别。我为此记录了一个宏,它起到了基本作用。

问题在于我希望宏搜索列名(因为列不一定是B& F中的列),并进行相应的排序。因此,我希望代码能够找到标题为" Asset Name" &安培; "行动",然后对它们进行排序。

这里是我录制的宏代码:(我把它放在50000的范围内,因为我希望它对于行数而言是动态的,而不是静态的,记录宏会这样做)

Cells.Select
ActiveSheet.sort.SortFields.Clear
ActiveSheet.sort.SortFields.Add Key:=Range("B2:B50000") _
    , SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
ActiveSheet.sort.SortFields.Add Key:=Range("F2:F50000") _
    , SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveSheet.sort
    .SetRange Range("A1:H50000")
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

要按列名排序,我想使用下面的分配列号,但我不知道在宏的记录部分再次在colNum中调用。

Dim colNum As Integer
colNum = WorksheetFunction.Match("Asset Name", ActiveSheet.Range("1:1"), 0)

2 个答案:

答案 0 :(得分:4)

btw定义一系列" 50000"行不归类为动态。请尝试以下

Sub test()
'Setup column names
Col1name = "Asset Name"
Col2name = "Action"

'Find cols
For Each cell In Range("A1:" & Range("A1").End(xlToRight).Address)
    If cell.Value = Col1name Then
        Col1 = cell.Column
    End If
    If cell.Value = Col2name Then
        Col2 = cell.Column
    End If
Next

'Below two line:- if they are blank e.g. column not found it will error so a small bit of error handling 
If Col1 = "" Then Exit Sub
If Col2 = "" Then Exit Sub

'Find last row - dynamic part
lastrow = ActiveSheet.Range("A100000").End(xlUp).Row

'Convert col numer to name
Col1 = Split(Cells(1, Col1).Address(True, False), "$")
Col2 = Split(Cells(1, Col2).Address(True, False), "$")

'Sort
With ActiveSheet.Sort
    .SortFields.Clear
    .SortFields.Add Key:=Range(Col1(0) & "2:" & Col1(0) & lastrow) _
        , SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    .SortFields.Add Key:=Range(Col2(0) & "2:" & Col2(0) & lastrow) _
        , SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal

    .SetRange Range("A1:H" & lastrow)
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

End Sub

答案 1 :(得分:0)

以下是一些缩写代码,可以为您提供所需的一切。

With ActiveSheet '<- set this worksheet reference properly
    With .Range("A1:H50000")
        .Cells.Sort Key1:=.Columns(Application.Match("Asset Name", .Rows(1), 0)), Order1:=xlAscending, _
                    Key2:=.Columns(Application.Match("Action", .Rows(1), 0)), Order2:=xlAscending, _
                    Orientation:=xlTopToBottom, Header:=xlYes
    End With
End With