as most of you know, you can only do text sorts on listview in report style, which is a big pain. MS provides an API method in the KB on how to sort by dates, but it is cumbersome, and it doesn't order the listitems, so after you use it, you can't do a for each listitem in listitems loop because the order of the listitems collection doesn't change. this code fixes all that, and doesn't even use any API
there is an example attached that will show you how it works.
Private Sub ListView2_ColumnClick(ByVal ColumnHeader As MSComctlLib.ColumnHeader)
ListView2.SortKey = ColumnHeader.Index - 1
If ListView2.SortKey = 1 Then ListView2.SortKey = 3 ' **** This column changes the key
ListView2.SortOrder = (ListView2.SortOrder - 1) * -1
ListView2.Sorted = True
End Sub
One way is to make all the numbers have the same length by
prepending spaces. Formatting with the '@' character
right justifies the number with spaces.
Code:
Private Sub Form_Load()
Dim n As String
Dim i As Long
'change this constant, depending on expected number length
' or calculate it
Const MaxLen As Long = 6
For i = 1 To 10
n = Format$(i, String$(MaxLen, "@"))
Debug.Print n, Len(n)
Next
End Sub
What that code shows is making the numbers the same length
with prepended spaces so the numbers will sort properly.
The code below shows using numbers in the 2nd column (SubItem(1))
Code:
Option Explicit
Private Sub Form_Load()
Dim i As Long
Dim Num As String
Const MaxLen As Long = 8 'change as necessary for the
'expected length of the numbers
Randomize
ListView1.Sorted = False
For i = 1 To 100
With ListView1.ListItems.Add
.Text = "Item " & i
Num = Format$(Int(Rnd * i * 1000) + 1, String$(MaxLen, "@"))
'you can see how this works by using '0' vice '@' in the above line
.SubItems(1) = Num
End With
Next
ListView1.SortKey = 1 'subitem(1)
ListView1.Sorted = True
End Sub
Private Sub ListView1_ColumnClick(ByVal ColumnHeader As MSComctlLib.ColumnHeader)
With ListView1
.SortKey = ColumnHeader.Index - 1
.SortOrder = .SortOrder Xor 1 'toggle ascending/descending
End With
End Sub