Friday, February 6, 2009

[vb6] Get object reference by its name in a form

In some cases you might want to activate an object in a form by given its name. To get it, you can use the controls collection of the form object:
  Private Sub Form_Load()
MsgBox GetCtlByName(Me, "Label1").Caption
End Sub

Private Function GetCtlByName( _
ByVal pForm As Form, _
ByVal pName$, _
Optional ByVal pIndex% = -1) As Control

On Error GoTo PROC_ERR

If pIndex < 0 Then
Set GetCtlByName = pForm.Controls(pName)
Else
Set GetCtlByName = pForm.Controls(pName, pIndex)
If pIndex <> GetCtlObj.Index Then GoTo PROC_ERR
End If

Exit Function

PROC_ERR:
Set GetCtlByName = Nothing
MsgBox "Error in procedure GetCtlByName for item name = '" & pName & "'.", vbExclamation
End Function 'GetCtlByName

No comments:

Post a Comment