Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sorting on more than 3 columns

Status
Not open for further replies.

kwill

Technical User
Aug 15, 2001
49
0
0
US
Can you sort on more than 3 columns in excel VBA? This is what I'm trying and it's not working.

Selection.Sort Key1:=Range("E2"), Order1:=xlAscending, Key2:=Range("K2") _
, Order2:=xlAscending, Key3:=Range("O2"), Order3:=xlAscending, Key4:=Range("h2"), order4:=xlAscending, key5:=Range("I2"), order5:=xlAscending, Header:= _
xlGuess, OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom
 
According to Excel help, three keys is all you get. The easiest way to get around this is to create a (temporary) extra column in which the values you're sorting on are concatenated (with appropriate padding), and use that as one of your keys.
Something like:
Code:
for i=3 to LastRow
   s=left(cells(i,15)+"                   ",20)
   s=s+left(cells(i,8)+"                   ",20)
   s=s+left(cells(i,9)+"                   ",20)
   cells(i,26)=s   'put values in Z column
next i
(now sort on keys E, K, Z)
(now you can delete column Z)

You'll have to adjust the code a little bit if some of the values are numeric.
Rob
 
Good point, that will work.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top