首页 > 解决方案 > 如何在 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

标签: vba

解决方案


你就在那儿,伙计!您可以简单地为您的地址数据创建另一个类并在您的客户类中实例化它。您只需要使用 VBA 的Set关键字来来回分配 Address 对象。Class_Initialize在 中实例化 Address 对象并将其设置NothingClass_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
    Street = pStreet
End Property

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

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

'... etc for other properties

推荐阅读