使用循环将属性分配给对象

Assigning Properties to Object using loop

我是对象的新手,Excel VBA 如果这是一个多余的问题,我深表歉意,但过去 2 天我一直在尝试加载一个具有以下属性的新对象存储在 Excel sheet.

我有大约 60 个属性需要加载。 我的主要子程序使用 class 中的加载子例程加载每个新实例。

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)

变量的数据以行格式存储在作品sheet中。

有没有简单简洁的编码方法?

您可以使用 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

我要补充一点,一个更健壮的对象处理方法需要一些封装,以防止意外的属性写入 因此,与其公开 Public property,不如将其保留 Private 并公开一些 Public Let 设置方法:

所以你的 Compound class 将是:

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