Problems referencing a series of controls on a header in a form in Access using VBA
In Access form designer I have created 73 Labels, named Label0 to Label72. The labels are in the form header of the form "MainScreen" and the snipped is called on upon the form opening.
I am trying to update their positions using this snippet, but it's not working, any idea why not or how to make it work?
I get the error "The expression you entered refers to an object that does not exist"
For X = 0 To 72
CtName = "Label" + Chr(X)
If ((X Mod 2) = 0) Then
Form_MainScreen.FormHeader.Controls(CtName).Top = 0
Else
Form_MainScreen.FormHeader.Controls(CtName).Top = 226
End If
Next
开发者_高级运维Thanks :)
There is a problem with this assignment statement:
CtName = "Label" + Chr(X)
The Chr(value) function returns the character whose ASCII code matches the value you pass to it. For example, when x=70, the value of CtName would be "LabelF" ... which is not what you want.
Use the CStr() function to convert a number to its string representation:
CtName = "Label" & CStr(x)
But you don't really even need the CStr() function; VBA will transform the number when performing concatenation (with the & operator):
CtName = "Label" & x
Finally, if your code snippet was from the form's Form_Open event, use Me to refer to the current form:
'Form_MainScreen.Controls(CtName).Top = 226 '
Me.Controls(CtName).Top = 226
Try
CtName = "Label" & X
String concatenation does not work with +
in VBA. (Well it does, but only if both operands are strings. IMHO, it's better to forget that and always use &
. See below.)
Also, Chr()
does not convert a number to a string, CStr()
does that. But it's unnecessary to call it explicitly, as VBA will do the necessary conversions on its own.
Correction: To be completely honest, string concatenation in fact does work with +
, see comments below. But I would definitely not recommend it, because it is error-prone when one of the operands is not a string. In my experience, it's always better to use &
to concatenate strings.
精彩评论