我有一组具有一堆属性的同一类对象。我想创建一个较小的集合,它只包含具有特定属性的特定值的对象,并且我希望能够多次为不同的属性调用sub,而不需要创建很多版本的sub。
以下是与问题相关的代码部分:
Sub MAIN()
Dim SplitArr(1 to 2) As Variant
SplitArr(1) = Y 'where Y is the value you are looking for
GetSplit arr:=SplitArr, X:=?? 'where ?? is the property you are looking at"
End Sub
Sub GetSplit(ByRef arr(), X as ??) 'unsure what type X should be
Dim collSplit As Collection
Set collSplit = New Collection
For Each v In coll
If v.X = arr(1) Then
collSplit.Add v
End If
Next v
Set arr(2) = collSplit
End Sub
所以应该发生的事情是GetSplit搜索主集合coll,如果任何对象的X属性等于Y,它会将对象添加到集合collSplit。最后,arr(2)设置为collSplit。
我不知道如何将属性名称传递给sub,所以任何帮助都会非常感激。
提前致谢!
答案 0 :(得分:0)
这是一个有效的例子......
另clsTest:
Public Prop1
Public Prop2
Public Prop3
常规模块:
Sub Tester()
Dim o, i
Dim col As New Collection
Dim colF As Collection
'populate some sample data...
For i = 1 To 10
Set o = New clsTest
o.Prop1 = i
o.Prop2 = i * 5
o.Prop3 = "Test"
col.Add o
Next i
Set colF = PropFilter(col, "Prop1", 2)
Debug.Print colF.Count '>> 1
Set colF = PropFilter(col, "Prop3", "Test")
Debug.Print colF.Count '>> 10
End Sub
Function PropFilter(col As Collection, propName As String, propValue)
Dim o
Dim rv As New Collection
For Each o In col
If CallByName(o, propName, VbGet) = propValue Then
rv.Add o
End If
Next o
Set PropFilter = rv
End Function