如何在VBA中的类中创建类

时间:2019-12-01 02:33:15

标签: vba

我正在尝试根据现有数据集创建一个类。这些列包括名称,街道地址,城市,州和邮政编码。我想创建一个带有名称和地址的类。在本课程中,我想再选一个包含街道地址,城市,州和邮编的地址类。

每个私有变量的代码如下(我没有城市,州或邮政编码的变量,但是我确定我需要它们):

Private pCustomerName As String

Public Property Let CustomerName(Value As String)
  pCustomerName = Value
End Property

Public Property Get CustomerName() As String
    CustomerName = pCustomerName
End Property

我想问的是,地址部分包含一个子类的区别是什么?

当前看起来像这样:

Public Property Let Address(Value As String) 
    pAddress = Value
End Property

Public Property Get Address() As String
    Address = pAddress
End Property

1 个答案:

答案 0 :(得分:2)

你就在那里!您可以简单地为您的地址数据创建另一个类,并在客户类中实例化它。您只需要使用VBA的Set关键字来来回分配Address对象。通常最好的做法是在Class_Initialize中实例化Address对象并将其在Nothing中设置为Class_Terminate,如下所示:

客户类别:

Option Explicit
Private pCustomerName As String
Private pAddress As AddressObj

Public Property Let CustomerName(value As String)
  pCustomerName = value
End Property

Public Property Get CustomerName() As String
    CustomerName = pCustomerName
End Property

Public Property Set CustomerAddress(value As AddressObj)
    Set pAddress = value
End Property

Public Property Get CustomerAddress() As AddressObj
    Set CustomerAddress = pAddress
End Property

Private Sub Class_Initialize()
    Set pAddress = New AddressObj
End Sub

Private Sub Class_Terminate()
    Set pAddress = Nothing
End Sub

地址类(我称它为AddressObj)

Option Explicit
Private pZipCode As Integer
Private pStreet As String
Private pState As String

Public Property Let ZipCode(value As Integer)
    pZipCode = value
End Property

Public Property Get ZipCode() As Integer
    ZipCode = pZipCode
End Property

Public Property Let Street(value As String)
    pStreet = value
End Property

Public Property Get Street() As String
    ZipCode = pStreet
End Property

Public Property Let State(value As String)
    pState = value
End Property

Public Property Get State() As String
    ZipCode = pState
End Property

'... etc for other properties