1

I am a bit of a rookie in vba and I am stuck on something which should be relatively easy: I have a marco specifying the column number from the headers names:

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

Now I want to sort my data based on this column:

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

However, my variable is integer while the command requests a range value. Can anyone help me in how to code it?

3 Answers 3

1

You only need this...

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
Sign up to request clarification or add additional context in comments.

1 Comment

@ShaiRado Yes that doesn't make any sense. I didn't look at it closely and copied OP's code. Lol Thanks for pointing that out. :)
0

Stating ActiveSheet is enough, there's no meaning to using ActiveWorkbook.ActiveSheet.

Use the code below to sort according to the numeric result you got for onomata.

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

2 Comments

What if I want to sort by more than 1 criterion? like first sort by column A and then by column B???
@e-gnacio sounds like a great new SO post, you should open a new one, this will allow other users (and me) to assist you
0
ActiveSheet.Sort.SortFields.Add Key:= ActiveSheet.Cells(onomata).EntireColumn

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.