2012-02-19 106 views
3

性能我有以下语法如下的一个类似13点的属性:阵列中VBA

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函数作为t他的财产被转换为一个功能。此外,For循环需要使用基于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 

第二个选项迭代通过“控制”用户窗体的集合:

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 

我在代码中发现了几件事

  • 括号是不必要的
  • 女巫属性“地址1”和“地址2”有些不对。你不能用名内部空间界定产权
  • 我相信LBOUND和UBound函数功能比使用数组的显示的界限
+0

谢谢出色答卷(更得心应手一点: – Kian 2012-02-19 22:48:42

+0

什么的MyObject1参考? – Kian 2012-02-20 00:20:02

+0

MyObject1是实现13个属性的类的实例 – Radek 2012-02-20 08:43:42