在 VBA 中对对象集合进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10273184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sorting a collection of objects in VBA
提问by Cutter
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.
另一种解决方案是将集合中的每个对象复制到一个对象数组中,并按它们的一个属性对它们进行排序,该属性的名称作为字符串传递给函数。但是我不知道如何使用作为字符串传递的属性名称来指向对象的属性。
回答by Authman Apatira
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.
想出你自己的 CompareKey 函数,如果 UDT 成员变量是 >、< 或 0,它将返回 true 或 false。您必须删除和重新添加的原因是因为您不能在 vb6/vba 集合对象中“交换”内部成员。
Best of luck
祝你好运
EDIT:
编辑:
To access a property you have the name of programmatically (as a string), use VB's CallByName
functionin the form:
要以编程方式访问具有名称的属性(作为字符串),请使用以下形式的VBCallByName
函数:
Result = CallByName(MyObject, "MyProperty", vbGet)