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!

Any advice on sorting a list box co

Status
Not open for further replies.

markSaunders

Programmer
Jun 23, 2000
196
GB
Any advice on sorting a list box control (in word) with the click of a command button?

Any help appreciated.

Cheers
Mark Saunders :)
 
hi

here is how you can do it

Sub SortItemInListBox()
'
'assume you have a userform and a listbox
'

Dim SortNow As New Collection, my_I As Integer
Dim i As Integer, j As Integer
Dim countItem As Integer
Dim Swap1, Swap2, Item, myItem

'add item to listbox
With UserForm1.ListBox1
.AddItem "Orange"
.AddItem "Apple"
.AddItem "Pear"
.AddItem "Durain"
.AddItem "Papaya"
End With

'add listbox item to collection
countItem = UserForm1.ListBox1.ListCount
For my_I = 0 To countItem - 1
myItem = UserForm1.ListBox1.List(my_I)
SortNow.Add Item:=myItem
Next

'Resume normal error handling
On Error GoTo 0

'Sort the collection
For i = 1 To countItem - 1
For j = i + 1 To countItem
If SortNow(i) > SortNow(j) Then
Swap1 = SortNow(i)
Swap2 = SortNow(j)
SortNow.Add Swap1, Before:=j
SortNow.Add Swap2, Before:=i
SortNow.Remove i + 1
SortNow.Remove j + 1
End If
Next j
Next i

'Clear list box
UserForm1.ListBox1.Clear

'add sorted item to listbox
For Each Item In SortNow
UserForm1.ListBox1.AddItem Item
Next Item

'Show the UserForm
UserForm1.Show
End Sub


Hope this helps. :)
LSTAN
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top