Sort Dates in a Listview, Correctly

By | 2019-08-25

This was a killer i saw it in the MSDN libraries and they went to much deep into it but there is an easier way…it works better.

In Visual basic 5.0 or 6.0 you cann’ot sort by date in the listview.

The problem is that when a value is entered in the cell, the control treats it as text. To overcome this problem, I created a extra column and set its width to zero so it would not be visible at run time.

I then modify the date format so it will appear evenly and as a number starting from year then month last day.

For Example:

lvListItems.SubItems(10) = Year(Search_Recordset.Fields("UPDATEDATE")) & _
   Format$(Month(Search_Recordset.Fields("UPDATEDATE")), "0#") & _
   Format$(Day(Search_Recordset.Fields("UPDATEDATE")), "0#")

Gave me:

20010110   From 1/10/2001
19951214   From 12 / 14 / 1995
19991101   From 11 / 1 / 1999

The EVEN number lengths will cause them to sort correctly as text. When the user clicked on the visible column, I just switched the column index to the hidden one.

Private Sub ListView1_ColumnClick(ByVal ColumnHeader As ComctlLib.ColumnHeader)
ListView1.SortKey = ColumnHeader.Index - 1
   If ListView1.SortKey = 1 Then lvwDisp.SortKey = 3 ' **** This column changes the key
   ListView1.SortOrder = (ListView1.SortOrder - 1) * -1
   ListView1.Sorted = True
End Sub

Author: dwirch

Derek Wirch is a seasoned IT professional with an impressive career dating back to 1986. He brings a wealth of knowledge and hands-on experience that is invaluable to those embarking on their journey in the tech industry.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.