Sort Method

  • Thread starter Thread starter Squid
  • Start date Start date
S

Squid

I have the following code. For some reason Key2 is not being sorted the way
I need it. For my santity, I tried switching between ascending/descending
in key2 and both results same. Any ideas why? The sort range is columns
A:AJ. Column B contains numbers and Column D contains dates.


Private Sub Workbook_BeforeClose(Cancel As Boolean)

'sort contract workbook (Sheet1) only if Settlement4b.xls is not open

Dim Wsheet As Worksheet
Set Wsheet = Worksheets("Sheet1") 'Contracts workbook

If Not WorkbookOpen("Settlement4b.xls") Then
With Wsheet
.Select
.Range("A1").Sort _
Key1:=.Range("B1"), Order1:=xlAscending, Header:=xlYes, _
Key2:=.Range("D1"), Order1:=xlDescending, Header:=xlYes
End With
End If


As aways Thanks!
Mike

End Sub
 
A few things. You don't want to sort range A1, you probably want
Range("A1").CurrentRegion, or maybe Range("A1:AJ500")
Next - you don't want to say Header:=xlyes twice, tho it doesn't seem to
hurt.
 
You shouldn't have Header in twice - header is for the entire sort area, not
for each key.

Other than that, I can't say. Try turning on the macro recorder and
sorting it manually. See what is recorded.
 
Your code is sorting only range A1. You need to sort all the
columns. Change

..Range("A1").Sort _
to
..UsedRange.Sort (...)


--
Cordially,
Chip Pearson
Microsoft MVP - Excel
Pearson Software Consulting, LLC
www.cpearson.com
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top