Sorting a collection of objects in VBA

吃可爱长大的小学妹 提交于 2020-06-25 04:38:23

问题


I'm trying to write a function that would sort a collection of objects. Since the objects are all of the same type (the same user-defined class), their property set is the same. Is it possible to discover the object's properties (through code) so as to put the collection in a bi-dimensional array, each row being for an object, each column for one of its property?

Another solution would be to copy each object from the collection to an array of objects, and sort them by one of their property, whose name is passed to the function as a string. But I don't see how I can point to the object's property using the property's name passed as a string.


回答1:


For a collection, it is best to sort it by it's Keys (that's what they're there for) -- but in case you don't have the keys list (lost your keys!):

'Give an input "Data As Collection"

    Dim vItm As Variant
    Dim i As Long, j As Long
    Dim vTemp As Variant

    For i = 1 To Data.Count – 1
        For j = i + 1 To Data.Count
            If CompareKeys(Data(i).myMemberKey, Data(j).myMemberKey) Then
                'store the lesser item
                vTemp = Data(j)

                'remove the lesser item
                Data.Remove j

                're-add the lesser item before the greater Item
                Data.Add vTemp, , i
            End If
        Next j
    Next i

Come up with your own CompareKey function which will return true or false if the UDT member variables are >, < or 0 to one another. The reason you have to delete and re-add is because you cannot 'swap' internal members in a vb6/vba collection object.

Best of luck

EDIT:

To access a property you have the name of programmatically (as a string), use VB's CallByName function in the form:

 Result = CallByName(MyObject, "MyProperty", vbGet)


来源:https://stackoverflow.com/questions/10273184/sorting-a-collection-of-objects-in-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!