2017-08-11 33 views
1

我是一个vba新手,我被困在应该相对容易的事情上: 我有一个marco从头文件名中指定列号:VBA编码排序数据的动态范围(列)

Dim onomata As Integer 
'find column named Name of ship 
Set acell = rows(1).Find(What:="Name of ship", LookIn:=xlValues, _ 
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ 
MatchCase:=False, SearchFormat:=False) 

If Not acell Is Nothing Then 
    onomata = acell.Column 
End If 

现在我想在此基础上栏我的数据进行排序:

Cells.Select 
ActiveWorkbook.ActiveSheet.Sort.SortFields.Clear 
ActiveWorkbook.ActiveSheet.Sort.SortFields.Add Key:=Range(*this is where I want to introduce the column*), _ 
    SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _ 
    xlSortTextAsNumbers 
With ActiveWorkbook.ActiveSheet.Sort 
    .SetRange Range("A1:AR100000") 
    .Header = xlYes 
    .MatchCase = False 
    .Orientation = xlTopToBottom 
    .SortMethod = xlPinYin 
    .Apply 
End With 

然而,我的变量是整数,而命令请求一个范围值。任何人都可以帮助我编写代码吗?

回答

0

陈述ActiveSheet就足够了,没有意义使用ActiveWorkbook.ActiveSheet

请使用下面的代码根据您为onomata得到的数字结果进行排序。

With ActiveSheet 
    .Sort.SortFields.Clear 
    .Sort.SortFields.Add Key:=Columns(onomata), SortOn:=xlSortOnValues, _ 
        Order:=xlAscending, DataOption:=xlSortTextAsNumbers 
End With 
+0

非常感谢!它完美的工作! –

+0

@ e-gnacio不客气 –

+0

如果我想按照一个以上的标准排序,该怎么办?就像首先按列A然后按列B排序 –

0
ActiveSheet.Sort.SortFields.Add Key:= ActiveSheet.Cells(onomata).EntireColumn 
1

你只需要这个......

Dim acell As Range 

'find column named Name of ship 
Set acell = Rows(1).Find(What:="Name of ship", LookIn:=xlValues, _ 
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ 
MatchCase:=False, SearchFormat:=False) 

If Not acell Is Nothing Then   
    ActiveSheet.Sort.SortFields.Clear 
    ActiveSheet.Range("A1").Sort key1:=acell.Offset(1, 0), order1:=xlAscending, Header:=xlYes 
End If 
+1

'ActiveWorkbook.ActiveSheet' ??? –

+0

@ShaiRado是的,这没有任何意义。我没有仔细查看它,并复制了OP的代码。大声笑感谢您指出。 :) – sktneer