7,763
社区成员
发帖
与我相关
我的任务
分享
Option Explicit
'保持属性值的局部变量
Private mvarMyName As String '局部复制
Private mvarMyClassBox As MyClassBox
Public Property Get MyClassBox() As MyClassBox
If mvarMyClassBox Is Nothing Then
Set mvarMyClassBox = New MyClassBox
End If
Set MyClassBox = mvarMyClassBox
End Property
Public Property Set MyClassBox(vData As MyClassBox)
Set mvarMyClassBox = vData
End Property
Private Sub Class_Terminate()
Set mvarMyClassBox = Nothing
End Sub
Public Property Let MyName(ByVal vData As String)
'向属性指派值时使用,位于赋值语句的左边。
'Syntax: X.MyName = 5
mvarMyName = vData
End Property
Public Property Get MyName() As String
'检索属性值时使用,位于赋值语句的右边。
'Syntax: Debug.Print X.MyName
MyName = mvarMyName
End Property
Option Explicit
'局部变量,保存集合
Private mCol As Collection
Public Function Add(MyName As String, MyClassBox As MyClassBox, Optional sKey As String) As MyClass
'创建新对象
Dim objNewMember As MyClass
Set objNewMember = New MyClass
'设置传入方法的属性
objNewMember.MyName = MyName
Set objNewMember.MyClassBox = MyClassBox
If Len(sKey) = 0 Then
mCol.Add objNewMember
Else
mCol.Add objNewMember, sKey
End If
'返回已创建的对象
Set Add = objNewMember
Set objNewMember = Nothing
End Function
Public Property Get Item(vntIndexKey As Variant) As MyClass
'引用集合中的一个元素时使用。
'vntIndexKey 包含集合的索引或关键字,
'这是为什么要声明为 Variant 的原因
'语法:Set foo = x.Item(xyz) or Set foo = x.Item(5)
Set Item = mCol(vntIndexKey)
End Property
Public Property Get Count() As Long
'检索集合中的元素数时使用。语法:Debug.Print x.Count
Count = mCol.Count
End Property
Public Sub Remove(vntIndexKey As Variant)
'删除集合中的元素时使用。
'vntIndexKey 包含索引或关键字,这是为什么要声明为 Variant 的原因
'语法:x.Remove(xyz)
mCol.Remove vntIndexKey
End Sub
Public Property Get NewEnum() As IUnknown
'本属性允许用 For...Each 语法枚举该集合。
Set NewEnum = mCol.[_NewEnum]
End Property
Private Sub Class_Initialize()
'创建类后创建集合
Set mCol = New Collection
End Sub
Private Sub Class_Terminate()
'类终止后破坏集合
Set mCol = Nothing
End Sub
Private Sub Command2_Click()
Dim o As MyClass
Dim obj As MyClassBox
Dim tmp As String
Dim i As Integer
'add
Set obj = New MyClassBox
For i = 1 To 100
Set o = New MyClass
tmp = "Name" & i
obj.Add tmp, obj
Next
'枚举
For Each o In obj
Debug.Print o.MyName
Next
Set o = Nothing
Set obj = Nothing
End Sub