我有13个属性,其语法与下面的语法类似:
Public Property Get Town() As String
Town = txtTown.Text
End Property
我希望能够使用循环并遍历这些属性的集合,而不是引用13个属性中的每一个。我将如何创建这些现有属性的数组。我非常希望他们保留有意义的名字。
修改
aSet IDCell = customerDBSheet.Range("CustomerDBEntryPoint").Offset(ID() - 1)
Dim properties()
properties = Array("ID()", "FirstName()", "LastName()", "Address 1()", "Address 2()", "Town()", "Postcode()", "Phone()", "Email()", "Sex()", "Username()", "PasswordHash()")
For i = 0 To 11
IDCell.Offset(1, i).Value = CStr(CallByName(frmCustomerEntry, properties(i), VbLet, ""))
Next i
我在最后一行收到错误:IDCell.Offset(1, i).Value = CStr(CallByName(frmCustomerEntry, properties(i), VbLet, ""))
最终代码:
Dim properties()
properties = Array("ID", "FirstName", "LastName", "Address1", "Address2", "Town", "Postcode", "Phone", "Email", "Sex", "Username", "PasswordHash")
For i = 0 To 11
IDCell.Offset(1, i).Value = CStr(CallByName(frmCustomerEntry, properties(i), VbMethod))
Next i
最后使用的代码,如上所示,特别使用从Radek的答案编辑的CallByName函数,因为属性已转换为函数。此外,For循环需要使用基于0的索引。此外,当第4个可选参数是空字符串文字时,抛出异常。
答案 0 :(得分:2)
您可以遍历属性名称数组:
Dim vProperties()
Dim vPropertyName
vProperties = Array("Town", "Street", "ZipCode")
For Each vPropertyName In vProperties
'''Do something
Next
现在是“棘手的”部分:“做某事”块只有vPropertyName设置为连续的属性名称。为了通过字符串变量的名称访问属性值,请使用CallByName函数:
...
For Each vPropertyName In vProperties
CallByName MyObject1, vPropertyName, VbLet, ""
Next
第二个选项迭代通过UserForm的“Controls”集合:
Dim vControl As Control
For Each vControl In UserForm1.Controls
If TypeName(vControl) = "TextBox" OR vControl.Name Like "MyPattern*" Then
'''Do something
End If
Next
编辑:
Dim properties()
properties = Array("ID", "FirstName", "LastName", "Address1", "Address2", "Town", "Postcode", "Phone", "Email", "Sex", "Username", "PasswordHash")
For i = LBound(properties) To UBound(properties)
IDCell.Offset(1, i).Value = CStr(CallByName(frmCustomerEntry, properties(i), VbLet, ""))
Next i
我在你的代码中发现了一些东西