2012-02-19 96 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