1

I want to sort a range of cells using Excel VBA macro

I have searched many websites but everywhere the examples show how to sort multiple columns with a single key

e.g. this example

Example Excel

In example above I want to sort cells A2 to A8, that's it. For this my code is

Range("A2:A8").Sort

But it is giving Runtime error 1004

What is the correct way to do it?

0

1 Answer 1

4

Try this

sub test()
Sheets("sheet1").Range("A2:A8").sort key1:=Range("A2:A8"), order1:=xlAscending, Header:=xlNo
End sub
Sign up to request clarification or add additional context in comments.

2 Comments

Range("A2:A8").Sort key1 := Range("A2") is enough. There seems to be an inconsistency in the documentation. All parameters in the Sort method are listed as being optional, which suggests that if you pass no parameters it defaults to what you get when you select a range and hit the sort button -- but it throws an error when you try to invoke it without any of the "optional" parameters.
Thanks Mick17 and @John Coleman. Finally done. Really, small mistake in documentation took hours of me.

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.