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?

Community
  • 1
  • 1
PIYUSH VAID
  • 13
  • 1
  • 5

1 Answers1

4

Try this

sub test()
Sheets("sheet1").Range("A2:A8").sort key1:=Range("A2:A8"), order1:=xlAscending, Header:=xlNo
End sub
Mick17
  • 196
  • 2
  • 12
  • 3
    `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. – John Coleman Dec 13 '16 at 15:36
  • Thanks Mick17 and @John Coleman. Finally done. Really, small mistake in documentation took hours of me. – PIYUSH VAID Dec 13 '16 at 16:41