VBA,编码动态范围(列)以排序数据

时间:2017-08-11 12:10:52

标签: excel vba excel-vba dynamic range

我在vba中是一个新手,我被困在应该相对容易的事情上: 我有一个marco从头名称中指定列号:

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

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

3 个答案:

答案 0 :(得分: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 :(得分:0)

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

答案 2 :(得分:0)

陈述ActiveSheet就足够了,使用ActiveWorkbook.ActiveSheet毫无意义。

使用以下代码根据onomata获得的数字结果进行排序。

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