BobSki
BobSki

Reputation: 1552

How to retrieve a VB Control instance, given its Name and Index?

If I have a string "cboEnoughMoney(0)", is it possible to retrieve the control from a control array that I have in my form, cboEnoughMoney?

In my code, I try to refer to the control in this way:

frm.Controls(sControlName).ListIndex = -1 

sControlName in this case is "cboEnoughMoney(0)" and I get an error that the control was not found.

EDIT: One of the issue's i'm having is trying to as above set the .listindex to -1, another one is where I actually try to get and set value to the combobox. In a function - i pass form name as parameter called frm.

In the code what has been done is this....

dim ctlData as string
If Frm.Controls(RS!CTRLname).ListIndex > 0 Then
      CtlData = Frm.Controls(RS!CTRLname).Value
Else
      CtlData = ""
End If

Any idea how I'd be able to do that with cboEnoughMoney(0)....

I assume I could follow your example and check

if instr(1,RS!CTRLname, "(")

but if there is, how would I refer to that particular control in frm

Upvotes: 1

Views: 384

Answers (2)

deblocker
deblocker

Reputation: 7697

It is just enough to look in the VB Properties Window: if you search "cboEnoughMoney(0)" you will find "cboEnoughMoney"(0) (without double quotes). Still the name is the same as a non-array control.

Properties Window

So, it is perfectly legal to refer to a VB Control with Name and Index, no need for a controls loop here:

If isControlsArray Then
    Set ctrl = Me.Controls(Name)(Index) '// array
Else
    Set ctrl = Me.Controls(Name) '// non array
End If

Upvotes: 3

Alex K.
Alex K.

Reputation: 175916

You cannot use the (index) part in a lookup via .Controls.

You can loop them manually & given that you can safely assume any control name with a ( is an array member and thus will have an Index property match on that:

Private Function GetControl(ByVal name As String) As VB.Control
    Dim pos As Long: pos = InStr(name, "(")

    If pos = 0 Then
        Set GetControl = Me.Controls(name) '// non array
    Else
        Dim index As Long
        index = Val(Mid$(name, pos + 1))   '// get index #
        name = Left$(name, pos - 1)        '// get base name

        For Each GetControl In Me.Controls
           If (GetControl.name = name) Then
                If (GetControl.index = index) Then Exit Function
            End If
        Next

        Set GetControl = Nothing
    End If
End Function

And then:

GetControl("cboEnoughMoney(1)").ListIndex = -1

Upvotes: 2

Related Questions