macros – 多级按列名sorting

我从一个我放入excel的程序下载了一组数据。 从这里,我想分两个级别的这个数据。 我为此logging了一个macros,这符合基本的目的。

问题是,我想让macrossearch列名(因为没有必要列总是在B&F),并相应地进行sorting。 因此,我想代码是这样的,它寻找标题为“资产名称”和“行动”,并对其进行sorting。

这里是我logging的macros代码:(我把范围放在50000,因为我希望它是dynamic的行数,而不是静态,哪些录制macros)

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 

为了整合按列名sorting,我想使用下面的指定列号,但我不知道在macros的logging部分再次调用colNum的位置。

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

顺便说一句,定义一个“50000”行的范围不归类为dynamic。 尝试下面

 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 eg 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 

这里有一些简短的代码,应该给你你正在寻找的一切。

 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