VBA Sort Parameter Syntax Issue

richlocus
2StarLounger
Posts: 164
Joined: 03 Oct 2015, 00:30

VBA Sort Parameter Syntax Issue

Post by richlocus »

Hello:
I have an Excel VBA sort that works properly as shown below when I have two sort keys (Only pertinent code shown):
_______________________________________________________
' THIS WORKS
With wksADF_Data.Sort
.SortFields.Clear
.SortFields.Add Key:= _
wksADF_Data.Columns("A"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
.SortFields.Add Key:= _
wksADF_Data.Columns("B"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
.SetRange rngADFExtractionSortRange
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.Apply
End With
_______________________________________________________
When I try to combine the two sort key statements by adding a column range, it fails with an error message. Why? And how can I create just one combined key with the COLUMNS parameter?
' THIS FAILS WITH ERROR MESSAGE
With wksADF_Data.Sort
.SortFields.Clear
.SortFields.Add Key:= _
wksADF_Data.Columns("A:B"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
.SetRange rngADFExtractionSortRange
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.Apply
End With

Thanks in advance.
Rich

User avatar
HansV
Administrator
Posts: 78487
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: VBA Sort Parameter Syntax Issue

Post by HansV »

Each SortField must be a single key - in your situation a single column.
If you want to sort on 2 columns, add 2 SortFields.
If you want to sort on 3 columns, add 3 SortFields.
Etc.
Best wishes,
Hans

richlocus
2StarLounger
Posts: 164
Joined: 03 Oct 2015, 00:30

Re: VBA Sort Parameter Syntax Issue

Post by richlocus »

Hans:
Thank you! I have been puzzling over this for a while this morning.
Regards,
Rich Locus