在Excel VBA中实例化另一个类中的对象

时间:2016-02-17 14:23:27

标签: vba excel-vba class subclass excel

我正在使用Excel VBA进行项目,其中我有许多数据集,每个数据集都填充了许多具有许多参数(例如治疗,结果等)的“患者”。为了解决这个问题,我打算创建一个名为“患者”的类,其中包含治疗和结果等属性。然后创建一个名为“dataset”的类,其公共属性为“patient”。我已经创建了类,我可以实例化一个数据集对象。但是,我该如何实例化患者对象,或理想情况下数据集对象中的一组患者对象呢?

数据集类模块:

Private pNumber As Integer
Public Patient As Patient

Public Property Get Number() As Integer
    Number = pNumber
End Property
Public Property Let Number(p As Integer)
    pNumber = p
End Property

患者类模块:

Private pID As Integer
Private pTreatment As Boolean
Private pResponse As Single

Public Property Get ID() As Integer
    ID = pID
End Property
Public Property Let ID(p As Integer)
    pID = p
End Property

Public Property Get Treatment() As Boolean
    Treatment = pTreatment
End Property
Public Property Let Treatment(p As Boolean)
    pTreatment = p
End Property

Public Property Get Response() As Single
    Response = pResponse
End Property
Public Property Let Response(p As Single)
    pResponse = p
End Property

主要模块

Sub main()

Dim data1 As Dataset
Set data1 = New Dataset

'code to instantiate array of patient within data1 here

End Sub

1 个答案:

答案 0 :(得分:2)

数据集将更好地指定这样的东西。

我会把课程称为课程,Patients

private colPatients as new collection

public function add(aPatient as patient)
  colPatients.add aPatient, aPatient.Id
end function

public property get count() as long
  count = colPatients.count
end property 

public property get items() as collection
  set items = colPatients
end property 

public property get item(vItem as variant) as patient
  set item = colPatients(vItem)
end property 

public sub remove(vItem as variant)
  colPatients.remove vItem
end sub 

所以要使用:

dim patientCollection as patients
Sub main()

Set patientCollection = New patients

'code to instantiate array of patient within data1 here
IDs = Array(1,2,3)
treats = array("x","y","z")

dim x as integer
dim p as patient
for x = lbound(IDs) to Ubound(IDs)
   set p= new patient
   p.id = IDs(x)
   p.treatment = treats(x)
   patientCollection.add p
   set p = nothing
next x


End Sub