Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Reference the value of a control by the controls name

Status
Not open for further replies.

pupop

Programmer
Oct 15, 2006
3
US
Is there a simple way to dynamicly reference the value in a control on a form if all I know is the name of the control?

this doesn't work:
me.controls(strControlName).value

I want to do something like this:

sub doSomething(strControlName as string)
if me.controls(strControlName).value > 50 then
msgbox "Value to large",,"Error"
end if
end sub

 
The following code is what I am using now, it is very inefficient but it gets the job done.

Function strGetValue(strName as string) as string
dim intCount as integer
intCount = me.controls.count
strGetValue = ""
do while intCount > 0
intCount = intCount - 1
if me.controls(intCount).name = strName then
strGetValue = me.controls(intCount).value
exit do
end if
loop
end function
 
pupop,

I guess you will be looking at TextBoxes which do not have a .value property, to return their values you'll have to use their .Text property. In the case of Labels you will have to retrurn their .Caption property etc.

Private Function strGetValue(strName as String) As String

Dim ctl As Control
For Each ctl In Controls()
If ctl.Name = strname Then
strGetValue = ctl.Text
End If
Next

End Function

The code above will crash if ctl has no .Text property so you can also check for the type of Control being looked at with lines like;

If TypeOf ctl is TextBox then
'do stuff
end if

HTH Hugh,
 
pupop,

Sorry I thought I was in the VB5 & 6 forum when I wrote the above. However it may also work for you in VBA.

redfaced Hugh,
 
That is a good point!, but in the application I am working on the control names I am passing to this function are all ComboBoxs
 
Why not passing the Control instead of its name ?

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ181-2886
 
If they are all comboboxes, how can their value be > 50? Or is "50" an actual item?

I also agree with PH that perhaps using the control - rather than its name - may be better.

I am not sure exactly what you are doing, especially the thing with all of the controls being comboboxes. Surely there is a commandbutton. Surely there are Labels. Are you do a TypeOf check to not consider other controls?

Gerry
My paintings and sculpture
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top