Search Tools Links Login

Collection Helper/Sorter

This method enables you to pass any collection 'byref' and then sort it by any property either ascending or descending.

Original Author: Paul Gorman


Public Enum Enum_colSortType
  colSortTypeString = 0
  colSortTypeNumeric = 1
  colSortTypeDateTime = 2
End Enum
Public Enum Enum_colSortOrder
  colSortOrderAscending = 0
  colSortOrderDescending = 1
End Enum

Public Sub SortCollection(ByRef oCollection As Collection, ByVal SortPropertyName As String, Optional ByVal KeyPropertyName As String, Optional ByVal SortType As Enum_colSortType = colSortTypeString, Optional ByVal SortOrder As Enum_colSortOrder = colSortOrderAscending)
Dim RS As ADODB.Recordset, oObj As Object, i As Long
Dim oSorted As Collection, sKeyField As String
  Set RS = New ADODB.Recordset
  RS.CursorLocation = adUseClient
  RS.CursorType = adOpenStatic
  Select Case SortType
    Case colSortTypeString
      RS.Fields.Append SortPropertyName, adVarChar, 100
    Case colSortTypeNumeric
      RS.Fields.Append SortPropertyName, adDouble
    Case colSortTypeDateTime
      RS.Fields.Append SortPropertyName, adDate
  End Select
  If KeyPropertyName <> "" Then
    sKeyField = "Key" & KeyPropertyName
    RS.Fields.Append sKeyField, adVarChar, 100
  End If
  Set oSorted = New Collection
  For i = oCollection.Count To 1 Step -1
    Set oObj = oCollection.Item(i)
    RS.Fields(SortPropertyName).Value = CallByName(oObj, SortPropertyName, VbGet)
    If KeyPropertyName <> "" Then
      RS.Fields(sKeyField).Value = CallByName(oObj, KeyPropertyName, VbGet)
    End If
    If KeyPropertyName <> "" Then
      oSorted.Add oObj, CallByName(oObj, KeyPropertyName, VbGet)
      oSorted.Add oObj
    End If
    oCollection.Remove i
  If SortOrder = colSortOrderAscending Then
    RS.Sort = SortPropertyName & " ASC"
    RS.Sort = SortPropertyName & " DESC"
  End If
  i = 1
  Do Until RS.EOF
    If KeyPropertyName <> "" Then
      oCollection.Add oSorted.Item(RS.Fields(sKeyField).Value), RS.Fields(sKeyField).Value
      oCollection.Add oSorted.Item(i)
    End If
    i = i + 1
End Sub

About this post

Posted: 2003-06-01
By: ArchiveBot
Viewed: 91 times


Visual Basic 6


No attachments for this post

Loading Comments ...


No comments have been added for this post.

You must be logged in to make a comment.