VBA自定义Collection类无法直接调用Add方法的问题咨询
问题原因与解决方法
问题原因
你定义的MyCollection类只是将一个Collection对象作为公开成员变量暴露,类本身并没有实现或包装Collection的Add等方法,因此外部必须通过varCollection.MyCollection这个成员路径才能调用原生Collection的方法,直接使用varCollection.Add自然无效。
解决方法
方法一:手动包装Collection的方法(推荐,封装性更好)
将内部的Collection设为私有,然后在类中手动定义与Collection同名的方法,内部调用私有Collection的对应方法:
' MyCollection类代码 Private internalCol As Collection Private Sub Class_Initialize() Set internalCol = New Collection End Sub ' 包装Add方法 Public Sub Add(ByVal Item As Variant, Optional ByVal Key As Variant, Optional ByVal Before As Variant, Optional ByVal After As Variant) internalCol.Add Item, Key, Before, After End Sub ' 按需包装其他需要的方法,比如Item、Remove、Count Public Property Get Item(ByVal Index As Variant) As Variant Set Item = internalCol.Item(Index) End Property Public Sub Remove(ByVal Index As Variant) internalCol.Remove Index End Sub Public Property Get Count() As Long Count = internalCol.Count End Property
修改后,在用户窗体中就可以直接使用varCollection.Add调用了。
方法二:实现Collection接口
让MyCollection类实现Collection接口,这样可以直接继承Collection的所有方法:
' MyCollection类代码 Implements Collection Private internalCol As Collection Private Sub Class_Initialize() Set internalCol = New Collection End Sub ' 实现Add方法 Private Sub Collection_Add(ByVal Item As Variant, Optional ByVal Key As Variant, Optional ByVal Before As Variant, Optional ByVal After As Variant) internalCol.Add Item, Key, Before, After End Sub ' 实现Item属性 Private Property Get Collection_Item(ByVal Index As Variant) As Variant Set Collection_Item = internalCol.Item(Index) End Property ' 实现Remove方法 Private Sub Collection_Remove(ByVal Index As Variant) internalCol.Remove Index End Sub ' 实现Count属性 Private Property Get Collection_Count() As Long Collection_Count = internalCol.Count End Property
这种方式需要实现Collection接口的所有成员,适合需要完整复用Collection所有功能的场景。
内容的提问来源于stack exchange,提问作者ibra
相关产品推荐
相关产品推荐

