Setting a control variable to a string name

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have a string array which has values for list box control names (it is a
string array because the values come from a form's OpenArgs value). I have
errors trying to use these names in a variable of type Control.

Dim cvarguement(2) as String
Dim cvlistbox as Control

cvarguement(0) = "Me!MyListBox"
cvstrlistbox = cvarguement(0)

Set cvlistbox = (cvstrlistbox)

returns object required error. Other attempts to use the set command to set
a Control type variable to a text variable's value gave a type mismatch error.

How can I set a Control type variable to a string value name of a control?
 
The short answer is that you can't, because a control is not a string! :-)

A slightly longer (and hopefully more helpful! :-) answer is that you need
to assign a reference to the object identified by the name, rather than the
name itself. Perhaps an example may help to clarify this ...

Private Sub Command4_Click()

Dim strControlNames() As String
Dim ctlControlObject As Control
Dim lngCounter As Long

ReDim strControlNames(Me.Controls.Count - 1)
For lngCounter = 0 To Me.Controls.Count - 1
strControlNames(lngCounter) = Me.Controls(lngCounter).Name
Next lngCounter

For lngCounter = LBound(strControlNames) To UBound(strControlNames)

'this is the key line - assigns a reference to an object, not a
string
Set ctlControlObject = Me.Controls(strControlNames(lngCounter))

If ctlControlObject.ControlType = acTextBox Then
Debug.Print ctlControlObject.Value
ElseIf ctlControlObject.ControlType = acComboBox Then
Debug.Print ctlControlObject.RowSourceType
ElseIf ctlControlObject.ControlType = acLabel Then
Debug.Print ctlControlObject.Caption
Else
Debug.Print ctlControlObject.Name
End If
Next lngCounter

End Sub
 
Pardon me, Brendan, but I don't think you are correct. Looking at the code
that Don posted, the only problem is that he did not qualify his control name.
All he really needed is
Set Me.cvlistbox = (cvstrlistbox)
instead of
Set cvlistbox = (cvstrlistbox)
 
Back
Top