Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 554
  • Last Modified:

Datewise Listbox Sorting in VB6

Hi,
I want to sort a listbox data datewise..
Listbox containing data like:

01-05-2004
10-11-2011
06-10-2009
26-01-1983
14-12-1966

I want to sort these listitems according to date..
Highest Date should be on top (Sorting in Descending order)

-Thanks :)
0
John-Paul75
Asked:
John-Paul75
  • 2
  • 2
1 Solution
 
kbireckiCommented:
One way to do this is to create another column which is hidden and contains a calculated number upon which the sort is performed in "Ascending" order.  That column would contain the result of subtracting the date value for the row from a far future date, (i.e. {far future date} - {date for today} = X, while {far future date} - {date for yesterday} = X+1, a larger value).
0
 
DhaestCommented:
Are you loading the data from a database ? If so, just load them with an order by from the database.

Another thing that you can do is to loop the complete list and reorder them
Dim i As Integer, x As Integer, remove As Integer
Dim date1 As String

For i = List1.ListCount - 1 To 0 Step -1
  date1 = List1.List(i)
  remove = i
    For x = 0 To i - 1
     If DateValue(List1.List(x)) < DateValue(date1) Then
      date1 = List1.List(x)
      remove = x
     End If
    Next x
 List1.RemoveItem remove
 List1.AddItem date1
Next i

Open in new window

0
 
John-Paul75Author Commented:
Dhaest Thanks your code almost worked... but try these:

01-05-2004
11-11-2011
11-10-2011
10-11-2011
06-10-2009
26-01-1983
14-12-1966

Now after sorting I got


14-12-1966
26-01-1983
01-05-2004
06-10-2009
10-11-2011
11-10-2011
11-11-2011

Look at the last 3 dates

These should be:

11-10-2011
10-11-2011
11-11-2011


-Please try to solve it.

Thanks
regards,
0
 
DhaestCommented:
That has something to do with your date-format on your system, because I don't have that issue here.

You can try to solve it with formatting the date
Private Sub OrderListBoxByDate()
Dim i As Integer, x As Integer, remove As Integer
Dim date1 As String

For i = List1.ListCount - 1 To 0 Step -1
      date1 = List1.List(i)
      remove = i
        For x = 0 To i - 1
         If DateValue(Format(List1.List(x), "DD/MM/YYYY")) < DateValue(Format(date1, "DD/MM/YYYY")) Then
          date1 = List1.List(x)
          remove = x
         End If
        Next x
     List1.RemoveItem remove
     List1.AddItem date1
    Next i
End Sub

Open in new window

0
 
John-Paul75Author Commented:
That worked ..Thanks alot
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now