Excel VBA自定义类,按属性值获取所有对象
我有一个类--“Class1”,它的属性--“attribute1”是字符串。 此属性的可能值为{1,2} Class1模块Excel VBA自定义类,按属性值获取所有对象,excel,class,object,vba,Excel,Class,Object,Vba,我有一个类--“Class1”,它的属性--“attribute1”是字符串。 此属性的可能值为{1,2} Class1模块 Private pattribute1 As String Public Property Get attribute1 () As String attribute1 = pattribute1 End Property Public Property Let attribute1 (Value As String)
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
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"
在我的主程序中,我需要检索attribute1值等于{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
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"
Dim col作为新集合
'创建对象
执行以下操作,同时将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
选项显式
子测试类1()
Dim col()作为新类别1
Dim obj As Class1
Dim j尽可能长
我的身份证很长
ReDim col(0到100)'请共享您当前的代码,如果您的属性的可能值为1,2,3,我们将很乐意提供帮助。使用int或enum不是更好吗。这很好。但我的第一个想法是在我的类1中构建一个函数,它接受像“1”或“2”这样的参数。这有可能吗?@gematzab有可能