VBA:是否可以创建一个行为类似于集合的类模块



我想知道是否可以创建自己的类,其行为类似于Collection。最好在示例中显示:

我目前的知识:

类别模块MyClass

Public oCollection As Collection
Public OtherData as Long
... 'Another Variables, Properties, Functions and Subs

模块

...
For Each oItem In MyClass.oCollection 'I need to address Collection inside the object
If oItem.OtherData = 0 Then
...

我喜欢实现的目标:

...
For Each oItem In MyClass 'Want to be able to iterate over oCollection just from Class
If oItem.OtherData = 0 Then
...

谢谢你的建议。

您可以通过使用Scripting.Dictionary和使用.items或.Keys.Methods返回数组来避免@CristianBuse描述的错误,这些数组可以对每个数组重复使用。

在回答您的问题时,包装集合或编写dictionary脚本是一种很好的做法,因为它允许您为宿主集合进行强类型。您还可以使用包装代码为输入值添加验证,或者扩展主机集合的功能

下面的代码显示了脚本字典的包装、add方法的验证以及简化向脚本字典添加数据的扩展。这些只是演示点的示例

Option Explicit
Private Type State
Host                As scripting.Dictionary

End Type
Private s               As State
Private Sub Class_Initialize()
Set s.Host = New scripting.Dictionary

End Sub

Public Property Get Item(ByVal ipKey As Long) As String
Item = s.Host.Item(ipKey)
End Property
Public Property Let Item(ByVal ipValue As String, ByVal ipKey As Long)
s.Host.Item(ipKey) = ipValue
End Property

Public Sub Add(ByVal ipKey As Long, ByVal ipValue As String)
If ipKey > 10 Then

Err.Raise _
5 + vbObjectError, _
"Size Error", _
"Object based on Class " & TypeName(Me) & " is limited to 0-9 members"

End

End If

s.Host.Add ipKey, ipValue

End Sub
Public Sub AddByIndex(ByVal ipArray As Variant)
Dim myArray As Variant

If Not IsArray(ipArray) Then

myArray = Array(ipArray)

Else

myArray = ipArray

End If

Dim myNextKey As Long
myNextKey = s.Host.keys(s.Host.Count - 1)
Do While s.Host.Exists(myNextKey)

myNextKey = myNextKey + 1

Loop


Dim myItem As Variant
For Each myItem In myArray

s.Host.Add myNextKey, myItem
myNextKey = myNextKey + 1

Next

End Sub
Public Function Items() As Variant
Items = s.Host.Items
End Function

所以你现在可以做

oclass.addbyindex Range("A1:A42").value

Dim myItem as Variant
For Each myItem in oClass.Items

相关内容

最新更新