Thread: VBA Sort
View Single Post
  #1   Report Post  
Posted to microsoft.public.excel.programming
Paul D.[_2_] Paul D.[_2_] is offline
external usenet poster
 
Posts: 18
Default VBA Sort

I recorded a macro to perform a sort of a single column on a worksheet then
rewrote the code to perform the same function when a button on a form is
pressed. This is the code I used to append a column in a worksheet with a
value of a textbox input and then sort the column:

Private Sub CommandButton1_Click()
'sngCountAns is the number of entries contained in the target column
strAddApt = Me.TextBox1.Value
If Len(strAddApt) = 4 Then
Sheets("Lists").Range("P" & sngCountAns + 1).Value = strAddApt
ActiveWorkbook.Worksheets("Lists").Sort.SortFields .Clear
ActiveWorkbook.Worksheets("Lists").Sort.SortFields .Add Key:=Range("P2"), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Lists").Sort
.SetRange Range("P2:P" & sngCountAns + 1)
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
UserForm_Activate
Me.TextBox1.Value = ""
Else
MsgBox ("Airport ID must be 4 digits to be added to the list")
End If
End Sub

I am using windows vista and Excel 2007. When I press the button the
operations performs exactly as I want it to. The file is saved in
compatability mode. When the program is opened with a pc using Excel2002, the
sort functions generates errors when the CommandButton1 is pressed.

I rewrote the code so that it works in Excel 2002 but now it generates
errors when I run the program with Excel 2007.

Can anyone help me with code that will sort a single column in all versions
of excel from 97 to 2007?
Thanks.
Paul