Accessing a member of the controls collection with a variable

G

Guest

I am trying to set the value of a set of controls on a form programmatically.
Using something like the following code:
Do While Not rs.EOF
sCtlName = "txt" + LTrim(Str(i))
Forms![main menu].Controls(sCtlName).Caption = rs![menu_item_description]
i = i + 1
rs.MoveNext
Loop
where the controls are named txt0, txt1, txt2 etc.. If I substitute "txt0"
into the line above it works fine but with the variable it gives me an
"object does not support this property or method" message.
How do I format this line so it will accept the variable for the control
name?
 
B

Brendan Reynolds

The prefix 'txt' is usually used for text boxes. Text boxes don't have a
Caption property. If 'txt0' works for you, then I guess 'txt0' must be a
different type of control, probably a label. What about the other controls
named 'txt...' - are they all labels? If one or more of them are text boxes,
or any other kind of control that doesn't have a Caption property, you would
get that error message.

BTW: You could replace these two function calls ...
LTrim(Str(i))
.... with one ...
CStr(i)

Unlike Str(), CStr() does not put a space in front of positive numbers, so
you won't need the call to LTrim().
 
G

Guest

Thanks. It is a text box. One of those ones where you spend hours looking
for the complex answer when the simple one is staring you in the face.

Brendan Reynolds said:
The prefix 'txt' is usually used for text boxes. Text boxes don't have a
Caption property. If 'txt0' works for you, then I guess 'txt0' must be a
different type of control, probably a label. What about the other controls
named 'txt...' - are they all labels? If one or more of them are text boxes,
or any other kind of control that doesn't have a Caption property, you would
get that error message.

BTW: You could replace these two function calls ...
LTrim(Str(i))
.... with one ...
CStr(i)

Unlike Str(), CStr() does not put a space in front of positive numbers, so
you won't need the call to LTrim().

--
Brendan Reynolds (MVP)

toolsgg said:
I am trying to set the value of a set of controls on a form
programmatically.
Using something like the following code:
Do While Not rs.EOF
sCtlName = "txt" + LTrim(Str(i))
Forms![main menu].Controls(sCtlName).Caption =
rs![menu_item_description]
i = i + 1
rs.MoveNext
Loop
where the controls are named txt0, txt1, txt2 etc.. If I substitute
"txt0"
into the line above it works fine but with the variable it gives me an
"object does not support this property or method" message.
How do I format this line so it will accept the variable for the control
name?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top