|
本帖最后由 lee1892 于 2015-3-26 13:55 编辑
VB中有大量的集合类,如Excel VBA中的WorkSheets和WorkSheet这样的,前者是后者的集合。
在实际使用中,我们会注意到这样的用法:
WorkSheets("Sheet1")
其等效于
WorkSheets.Item("Sheet1")
实际上利用的是VB中的默认属性,在VBA中这个属性是不显示的,但可以通过如下办法手动添加:
1、导出类模块文件
2、用文本编辑器编辑导出的文件,在所需要设置的默认属性段内加一行:- Attribute Value.VB_UserMemId = 0
复制代码 3、移除VBA中的该文件,导入编辑过的类模块文件
以本贴附件为例,在文本编辑器中打开会是这样的- VERSION 1.0 CLASS
- BEGIN
- MultiUse = -1 'True
- End
- Attribute VB_Name = "CupCakes"
- Attribute VB_GlobalNameSpace = False
- Attribute VB_Creatable = False
- Attribute VB_PredeclaredId = False
- Attribute VB_Exposed = False
- Option Explicit
- Private colCakes As Collection
- Private Sub Class_Initialize()
- Set colCakes = New Collection
- End Sub
- Private Sub Class_Terminate()
- Dim oCake As CupCake
- For Each oCake In colCakes
- Set oCake = Nothing
- colCakes.Remove 1
- Next
- Set colCakes = Nothing
- End Sub
- Property Get Item(Index) As CupCake
- Attribute Value.VB_UserMemId = 0
- Set Item = colCakes(Index)
- End Property
- Property Get Count() As Integer
- Count = colCakes.Count
- End Property
- Public Function Add(Optional ByVal Name As String) As CupCake
- If Len(Name) = 0 Then
- Name = "CupCake " & colCakes.Count + 1
- End If
- Set Add = New CupCake
- Add.Name = Name
- colCakes.Add Add, Name
- End Function
复制代码 这样一来,就可以把 Item 属性作为默认属性,从而在实际使用中可以省略掉,比如附件中的测试过程:- Sub Test()
- Dim oCakes As New CupCakes, oCake As CupCake
- Dim i%
- With oCakes
- Debug.Print oCakes.Count
- Set oCake = .Add("MyCake")
- With oCake
- .Size = ckMiddle
- .CakeType = ckChocolate
- End With
- With .Add("HisCake")
- .Size = ckBig
- .CakeType = ckStrawberry
- End With
- End With
- With oCakes("MyCake")
- Debug.Print .Name; .Size; .CakeType
- Debug.Print
- End With
- With oCakes.Item("MyCake")
- Debug.Print .Name; .Size; .CakeType
- Debug.Print
- End With
- For i = 1 To oCakes.Count
- With oCakes(i)
- Debug.Print .Name; .Size; .CakeType
- End With
- Next
- oCakes.Remove "MyCake"
- Debug.Print oCakes.Count
- ' 下述For Each不能使用
- 'For Each oCake In oCakes
- ' Debug.Print oCake.Name
- 'Next
- Set oCakes = Nothing
- End Sub
复制代码 但这个办法存在一个问题,就是这样的集合类是不支持 For Each 循环的。
欢迎讨论~
=============
附件加了3楼的办法
要支持 For Each 的话,需要如上述导出到文件,再用文本编辑器编辑,再导入。添加下述代码- Public Function NewEnum() As IUnknown
- Attribute NewEnum.VB_UserMemId = -4
- Set NewEnum = colCakes.[_NewEnum]
- End Function
复制代码 此处的 colCakes 是用来存放类CupCake的内部集合对象,_NewEnum是集合对象的一个隐藏的方法需要用 [ ] 标识,前面一句设该方法的 UserMemId 为-4 是在VB中隐藏该方法,但在VBA中实际上并没有隐藏,但在VBA中必须设置才能正常使用。 |
评分
-
5
查看全部评分
-
|