Link to home
Start Free TrialLog in
Avatar of mcs26
mcs26

asked on

VBA Collections

Hi,

I found some code (bottom of post) that sorts a collection by the field I request which works perfectly. The question I have is how to do this for two properties, i.e. by date then time?

Any help would be great.

Thanks

Mark
Private Function SortCollection(Col As Collection, psSortPropertyName As String, _
                                            pbAscending As Boolean, Optional psKeyPropertyName As String) As Collection

Dim obj As Object
Dim i As Integer
Dim j As Integer
Dim iMinMaxIndex As Integer
Dim vMinMax As Variant
Dim vValue As Variant
Dim bSortCondition As Boolean
Dim bUseKey As Boolean
Dim sKey As String
   
    bUseKey = (psKeyPropertyName <> "")
   
    For i = 1 To Col.Count - 1
        Set obj = Col(i)
        vMinMax = CallByName(obj, psSortPropertyName, VbGet)
        iMinMaxIndex = i
       
        For j = i + 1 To Col.Count
            Set obj = Col(j)
            vValue = CallByName(obj, psSortPropertyName, VbGet)
           
            If (pbAscending) Then
                bSortCondition = (vValue < vMinMax)
            Else
                bSortCondition = (vValue > vMinMax)
            End If
           
            If (bSortCondition) Then
                vMinMax = vValue
                iMinMaxIndex = j
            End If
           
            Set obj = Nothing
        Next j
       
        If (iMinMaxIndex <> i) Then
            Set obj = Col(iMinMaxIndex)
           
            Col.Remove iMinMaxIndex
            If (bUseKey) Then
                sKey = CStr(CallByName(obj, psKeyPropertyName, VbGet))
                Col.Add obj, sKey, i
            Else
                Col.Add obj, , i
            End If
           
            Set obj = Nothing
        End If
       
        Set obj = Nothing
    Next i
   
    Set SortCollection = Col
     
End Function
ASKER CERTIFIED SOLUTION
Avatar of ChloesDad
ChloesDad
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial