我正在嘗試使用 vba 中的類,但我沒有找到任何與管理物件內的物件(例如類內的陣列或集合)相關的檔案。
假設我有一個班級人員和一個班級地址,我想管理一個人的地址。
地址
Private pStreet as String
Private pZip as Int
Public Property Let Street(val As String)
pStreet = val
End Property
Public Property Get Street() As String
Street = pStreet
End Property
Public Property Let Zip(val As String)
pZip = val
End Property
Public Property Get Zip() As String
Zip = pZip
End Property
人
Private pName As String
Private pSurname As String
Private pAddresses As Collection
Public Property Let Name(val As String)
pName = val
End Property
Public Property Get Name() As String
Name = pName
End Property
Public Property Let Surname(val As String)
pSurname = val
End Property
Public Property Get Surname() As String
Surame = pSurname
End Property
Private Sub Class_Initialize()
Set pAddresses = New Collection
End Sub
Private Sub Class_Terminate()
Set pAddresses = Nothing
End Sub
Public Sub addAddress(ByVal val As Address)
pAddresses.Add val
End Sub
Public Property Get Addresses() As Collection
Set Addresses = pAddresses
End Property
Public Property Get Address(ByVal Index As Long) As Address
Set Address = pAddresses(Index)
End Property
模塊1
Sub test()
Dim x As Person
Set x = New Person
Dim a1 As Address
Set a1 = New Address
Dim a2 As Address
Set a2 = New Address
x.Name = "Mark"
x.Surname = "Doe"
a1.Street = "first avenue 213"
a1.Zip = "41242"
a2.Street = "second avenue 213"
a2.Zip = "55242"
x.addAddress a1
x.addAddress a2
Debug.Print x.Address(0)
End Sub
我應該如何處理 person 類中的地址集合?例如,我如何檢索集合的所有地址或第二個地址?x.addresses(1) 不起作用。
uj5u.com熱心網友回復:
該類Person應包含地址集合,以避免必須擴展和保留陣列。一旦類被初始化/終止,集合就應該被初始化/終止。
看一個例子:
Private pAddresses as Collection
Private Sub Class_Initialize()
Set pAddresses = New Collection
End Sub
Private Sub Class_Terminate()
Set pAddresses = Nothing
End Sub
該類可以通過用于回圈的屬性或通過索引訪問的單個地址公開整個地址集合。
Public Property Get Addresses() As Collection
Set Addresses = pAddresses
End property
Public Property Get Address(ByVal Index As Long) As Address
Set Address = pAddresses(Index)
End property
然后你可以回圈:
Dim p As Person, a As Address
For Each a In p.Addresses
a.Zip = ...
Next
或者通過索引獲取單個地址:
Set a = p.Addresses(1)
最后,一個簡單的Add方法,給這個人添加一個地址:
Public Sub AddAddress(ByVal param As Address)
pAddresses.Add param
End Sub
您還可以通過提供地址物件和索引來使用屬性添加(或替換)地址,但我不知道它在您的情況下有多大用處。當然,您需要確保 Index 是有效的。
Public Property Let Address(ByVal Index As Long, ByVal param As Address)
pAddresses.Add param, Index
End property
然后呼叫它:
p.Addresses(Index) = a
要強制執行Set關鍵字,因為我們正在處理物件,請更改Let為Set. 然后,您需要設定它:
Set p.Addresses(Index) = a
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/454698.html
下一篇:將單詞中的字母分類為元音和輔音
