2017-02-27 198 views
0

我有一個類 - 「Class1」的屬性 - 「attribute1」作爲字符串。 該屬性的可能vlaues是{1,2}VBA自定義類,通過屬性值獲取所有對象

Class 1模塊

Private pattribute1 As String 

    Public Property Get attribute1() As String 
     attribute1 = pattribute1 
    End Property 

    Public Property Let attribute1 (Value As String) 
     pattribute1 = Value 
    End Property 

以我主程序,我需要與等於ATTRIBUTE1值檢索所有的對象{1}。

主模塊

Dim col As New Collection 

    'Create objects 
    Do While j <= 5 

     Dim obj As Class1 
     Set obj= New Class1 
     if j<3 then 
      obj.attribute1 = "1" 
     else 
      obj.attribute1 = "2" 
     end if 
     j = j + 1 
    Loop 

    Set col = 'get all objects from Class1 with attribute equal to "1" 

這是最有效的方式做到這一點?

謝謝您提前。

+0

請分享你當前的代碼,我們會很樂意幫助 –

+0

如果你的屬性的可能的值是1,2,3,豈不是更好地使用int或枚舉。 – basslo

回答

0

Main模塊中修改代碼以下面的代碼:

Option Explicit 

Sub TestClass1() 

Dim col() As New Class1 
Dim obj As Class1 
Dim j As Long 
Dim id As Long 

ReDim col(0 To 100) '<-- init to large size, will optimize later 

'Create objects 
Do While j <= 5 
    Set obj = New Class1 
    If j < 3 Then 
     obj.attribute1 = "1" 
     Set col(id) = obj '<-- add to col when equals 1 
     id = id + 1 
    Else 
     obj.attribute1 = "2" 
    End If 
    j = j + 1 
    Set obj = New Nothing 
Loop 

ReDim Preserve col(0 To id - 1) '<-- resize array to populated size 

End Sub 
+0

這工作正常。但我的第一個想法是在我的class1中構建一個接受像「1」或「2」這樣的參數的函數。這可能嗎? – gematzab

+0

@gematzab這是可能的 –