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 Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sorting Contents of a List Box 1

Status
Not open for further replies.

Arthur1

MIS
Apr 8, 2003
28
US
I have the code below to populate a list box:
Now I want to be able to sort the two columns in the list box when the user click on a command button which I will place on top of the columns. Any help would be appreciated.



Private Sub UserForm_Activate()
Dim oFSO As Object, oFolder As Object, oFile As Object
Dim sPath As String

sPath = "C:2003\"

'Creates a system object so we can get access to Files and Folders
Set oFSO = CreateObject("Scripting.FileSystemObject")

'If a folder exixts in the specifed path (This might not be necessary)
If oFSO.FolderExists(sPath) Then

'Set the folder to the path we specifed
Set oFolder = oFSO.GetFolder(sPath)

'Initalize counter
C = 0

'Loop through for each file in the folder
For Each oFile In oFolder.Files

'Increment the counter
C = C + 1

'Only get the file name and the creation date for excel files
If LCase$(Right$(oFile.Name, 4)) = ".xls" Then

'Fill in the list box with the name of the file and the date
ListBox1.AddItem (oFile.Name)
ListBox1.List(C - 1, 1) = (oFile.DateLastModified)

End If
Next oFile

Set oFolder = Nothing
Else
MsgBox "Cannot find " & sPath
End If

End Sub
 
Hi,

Try this code, it work for the date sorting, and do something similar to sort it back for name.

Private Sub cmdSortD_Click()
Dim colDate As New Collection
Dim colFile As New Collection
Dim intN As Integer
Dim intC As Integer
Dim Flag As Boolean
Flag = True
colFile.Add ListBox1.List(1, 0), ListBox1.List(1, 0)
colDate.Add CStr(ListBox1.List(1, 1)), ListBox1.List(1, 0)
For intN = 2 To ListBox1.ListCount - 1
For intC = 1 To colFile.Count
If ListBox1.List(intN, 1) < colDate.Item(intC) Then
colFile.Add ListBox1.List(intN, 0), ListBox1.List(intN, 0), intC
colDate.Add CStr(ListBox1.List(intN, 1)), ListBox1.List(intN, 0), intC
Flag = False
Exit For
End If
Next intC
If Flag Then
colFile.Add ListBox1.List(intN, 0), ListBox1.List(intN, 0)
colDate.Add CStr(ListBox1.List(intN, 1)), ListBox1.List(intN, 0)
End If
Next intN
ListBox1.Clear
For intN = 1 To colFile.Count
ListBox1.AddItem colFile.Item(intN)
ListBox1.List(intN - 1, 1) = colDate.Item(intN)
Next intN
End Sub


Jean-Paul
Montreal
jp@solutionsvba.com
mtljp2@sympatico.ca
 
Thanks for the code. I will have to analyze the code a little more. It seems to be sorting out the lowest date from the list box? I am not sure why. But thanks again.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top