VB VarUserMemId
VB_VarUserMemId
(用於模組範圍變數)和 VB_UserMemId
(用於過程)屬性在 VBA 中主要用於兩件事。
指定類的預設成員
將 Collection
封裝的 List
類需要具有 Item
屬性,因此客戶端程式碼可以執行以下操作:
For i = 1 To myList.Count 'VBA Collection Objects are 1-based
Debug.Print myList.Item(i)
Next
但是在 Item
屬性上將 VB_UserMemId
屬性設定為 0,客戶端程式碼可以執行以下操作:
For i = 1 To myList.Count 'VBA Collection Objects are 1-based
Debug.Print myList(i)
Next
在任何給定的類中,只有一名成員可以合法地擁有 VB_UserMemId = 0
。對於屬性,請在 Get
訪問器中指定屬性:
Option Explicit
Private internal As New Collection
Public Property Get Count() As Long
Count = internal.Count
End Property
Public Property Get Item(ByVal index As Long) As Variant
Attribute Item.VB_Description = "Gets or sets the element at the specified index."
Attribute Item.VB_UserMemId = 0
'Gets the element at the specified index.
Item = internal(index)
End Property
Public Property Let Item(ByVal index As Long, ByVal value As Variant)
'Sets the element at the specified index.
With internal
If index = .Count + 1 Then
.Add item:=value
ElseIf index = .Count Then
.Remove index
.Add item:=value
ElseIf index < .Count Then
.Remove index
.Add item:=value, before:=index
End If
End With
End Property
使用 For Each
迴圈結構建立一個可迭代的類
使用魔術值 -4
,VB_UserMemId
屬性告訴 VBA 該成員產生一個列舉器 - 允許客戶端程式碼執行此操作:
Dim item As Variant
For Each item In myList
Debug.Print item
Next
實現此方法的最簡單方法是在內部/封裝的 Collection
上呼叫隱藏的 [_NewEnum]
屬性 getter; 識別符號需要括在方括號中,因為前導下劃線使其成為非法的 VBA 識別符號:
Public Property Get NewEnum() As IUnknown
Attribute NewEnum.VB_Description = "Gets an enumerator that iterates through the List."
Attribute NewEnum.VB_UserMemId = -4
Attribute NewEnum.VB_MemberFlags = "40" 'would hide the member in VB6. not supported in VBA.
'Gets an enumerator that iterates through the List.
Set NewEnum = internal.[_NewEnum]
End Property