正如其他人所说,没有直接的方法来循环对象属性。我有一个电子表格,其中存储了许多我需要在运行时读取的值,类似于你的。我发现做到这一点的最佳方法是使用CallByName
允许您按名称设置或获取属性的方法。
现在,有些人可能会说初始设置是多余的,但我经常添加和删除这些属性,因此对代码进行同样的操作更加麻烦。因此,这种方法的美妙之处在于您可以经常修改您的属性数量,而无需更改此代码。CallByName
您可以从这里 使用令人敬畏的功能: https ://stackoverflow.com/a/5707956/1733206
然后对于您的示例,我将在我的poss
集合中执行以下操作(请注意,这不会执行您可能想做的任何错误检查等):
Public Sub ReadInData()
Dim vInputs As Variant, ii As Integer, jj As Integer, cp As pos
Dim sPropertyName As String, vPropertyValue As Variant
'Raead in the data. I've set it from the activesheet, you can do it how you like
With ActiveSheet
vInputs = .Range(.Cells(1, 1), .Cells(.UsedRange.Rows.Count, .UsedRange.Columns.Count)).Value2
End With
'Look through the rows of data, one row per 'pos' object
For ii = LBound(vInputs, 1) + 1 To UBound(vInputs, 1)
'Set up your object
Set cp = New pos
'Loop through the columns of data eg Clutch, wiper, etc
For jj = LBound(vInputs, 2) To UBound(vInputs, 2)
'Put in seperate variables so its easy to see what's happening
sPropertyName = vInputs(1, jj)
vPropertyValue = vInputs(ii, jj)
'Use the callable method to set the property (from here: https://stackoverflow.com/a/5707956/1733206)
Call SetProperty(sPropertyName, vPropertyValue, cp)
Next jj
Me.Add cp
Set cp = Nothing
Next ii
End Sub
这是工作簿中的一个示例:https ://dl.dropboxusercontent.com/u/13173101/VBAObject.xlsm
编辑: 由于您将经常更改对象,因此我包含了另一个非常方便的模块,并且实际上会根据工作表中的列标题为您编写类。pos
这意味着如果您添加另一列,它会将这些属性添加到对象中!它假定所有属性都是字符串,但您可以修改以适应。