I have 13 properties following similar syntax as the one below:
Public Property Get Town() As String
Town = txtTown.Text
End Property
I would like to be able to use a loop and iterate through a collection of these properties instead of referencing each of the 13 properties. How would I go about creating an array of these prexisting properties. I would very much prefer for them to keep their meaningful names.
EDIT:
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
I get an error on the line before last: IDCell.Offset(1, i).Value = CStr(CallByName(frmCustomerEntry, properties(i), VbLet, ""))
Final Code:
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
The code used in the end, shown above specifically uses the CallByName function edited from Radek’s answer as the property was converted to a function. Furthermore, the For loop needed to use a 0-based index. Also, an exception was thrown when the 4th optional parameter was an empty string literal.
You can iterate through array of property names:
Dim vProperties()
Dim vPropertyName
vProperties = Array("Town", "Street", "ZipCode")
For Each vPropertyName In vProperties
'''Do something
Next
Now is the “tricky” part: “Do something” block have only vPropertyName set to consecutive property names. In order to access property value by its name from string variable use CallByName function:
...
For Each vPropertyName In vProperties
CallByName MyObject1, vPropertyName, VbLet, ""
Next
The second option iteration through “Controls” collection of UserForm:
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
EDIT:
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
I found few things in your code
- Parentheses are unnecessary
- Something is wrong witch properties “Address 1” and “Address 2”. You can’t define property with space inside the name
- I believe that the LBound and UBound functions are little bit more handy than using explicit boundaries of array
Tags: arraysvba