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

标签 vba excel class subclass

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

数据集类模块:

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

最佳答案

数据集将被更好地指定为这样的。

我会按照预期的名称来命名该类,因此患者:

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

关于vba - 在Excel VBA中实例化另一个类中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35459305/

相关文章:

python - 将 CSV/Excel 文件转换为格式为表格的 EXCEL 文件

类命名困惑

c++ - 类模板的所有实例化是否可以共享同一个模板独立成员函数?

vba - 如何将 excel-vba 宏限制在一张纸上?

excel - 用VBA计算百分比

excel - 错误1004 : Microsoft Excel cannot paste the data

c# - 以编程方式更改 Excel 中的宏文本

Excel:从固定列中获取相对行值的最佳方法是什么?

java - 使用 excel 单击 Javascript 按钮

java - 如何将包中的类导入到另一个包中?