2015-08-26 77 views
0

我有一组属性的同一类的对象的集合。我想创建一个较小的集合,它只包含具有特定属性的特定值的对象,并且我希望能够针对不同属性多次调用子集,而无需制作大量子版本。将类属性名称传递给子集以搜索集合

下面是部分代码是相关的问题:

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搜索通过主收集,科尔,如果任何物体的存在有X属性等于到Y它会将对象添加到collSplit集合中。最后arr(2)被设置为collSplit。

我不知道该怎么办是将属性名称传递给子,所以任何帮助将不胜感激。

在此先感谢!

+0

将 '变形' 工作,它将使数字和字符串。 –

+0

@ScottCraner我假设Variant是sub的正确类型,但我不知道要在sub MAIN()中设置'??'等于什么,或者我的符号可以在GetSplit中使用'vX',因为X只会是一个变量,而不是对物业的引用 – JChristen

回答

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 
+0

完美!谢谢蒂姆! – JChristen