如果这是一个多余的问题,我是对象和Excel VBA的新手,所以道歉,但我花了最近两天的时间尝试加载一个存储在Excel工作表中的属性的新对象。
我有大约60个需要加载的属性。 我的主子程序使用类中的Load子例程加载每个新实例。
Sub Main()
Dim loadedCompound As Compound 'my class
Set loadedCompound = New Compound
loadedCompound.Load Selection 'a sub in Compound class
我尝试创建一个数组,每个变量名称作为一个级别,并循环遍历数组,迭代器链接到数组和偏移值。但是VBA不会让我使用数组字符串作为变量。
Sub Main()
Dim loadedCompound As Compound 'my class
Dim arrayProperties() As String 'Array of the class property names
Set loadedCompound = New Compound
arrayProperties =
Split(",CDKFingerprint,SMILES,NumBatches,CompType,MolForm",",")
For i = 1 To UBound(arrayProperties)
loadedCompound.arrayProperties(i) = Selction.Offset(0, i)
Next i
目前,我手动加载每个变量,如下所示,但它的冗余代码很多,而且可读性差。
Sub Load(ARID As Range)
pCDKFingerprint = ARID.Offset(0, 1)
pSMILES = ARID.Offset(0, 2)
pNumBatches = ARID.Offset(0, 3)
pCompType = ARID.Offset(0, 4)
pMolForm = ARID.Offset(0, 5)
pMW = ARID.Offset(0, 6)
pChemName = ARID.Offset(0, 7)
pDrugName = ARID.Offset(0, 8)
pNickName = ARID.Offset(0, 9)
pNotes = ARID.Offset(0, 10)
pSource = ARID.Offset(0, 11)
pPurpose = ARID.Offset(0, 12)
pRegDate = ARID.Offset(0, 13)
pCLOGP = ARID.Offset(0, 14)
pCLOGS = ARID.Offset(0, 15)
变量的数据以rowformat格式存储在工作表中。
有一种简单易懂的方法来编码吗?
答案 0 :(得分:1)
您可以使用CallByName()功能:
arrayProperties = Split(",CDKFingerprint,SMILES,NumBatches,CompType,MolForm", ",")
For i = 1 To UBound(arrayProperties)
CallByName loadedCompound, "p" & arrayProperties(i), VbLet, Selection.Offset(0, i).Value
Next i
我补充说,更强大的对象处理方法需要一些封装,以防止意外的属性写入
因此,不要公开公共 property
,而是保留私有并公开一些公共 Let
方法来设置它:
所以你的Compound
课程将是:
Private pCDKFingerprint As Variant
Private pSMILES As Variant
....
Public Property Let CDKFingerprint(val As Variant)
pCDKFingerprint = val
End Property
Public Property Let SMILES(val As Variant)
SMILES = val
End Property
....
因此您的代码将按如下方式利用它:
Sub Main()
Dim loadedCompound As Compound 'my class
Dim arrayProperties() As String 'Array of the class property names
Dim i As Long
Set loadedCompound = New Compound
arrayProperties = Split(",CDKFingerprint,SMILES,NumBatches,CompType,MolForm", ",")
For i = 1 To UBound(arrayProperties)
CallByName loadedCompound, arrayProperties(i), VbLet, Selection.Offset(0, i).Value
Next i
End Sub