Parent Property Example

The following example uses the Parent property to refer to the control or form that contains a specific control.

To use this example, copy this sample code to the Declarations portion of a form. Make sure that the form contains:

Dim MyControl As Object
Dim MyParent As Object
Dim ControlsIndex As Integer

Private Sub UserForm_Initialize()
    ControlsIndex = 0
    CommandButton1.Caption = "Get Control and Parent"
    CommandButton1.AutoSize = True
    CommandButton1.WordWrap = True
End Sub

Private Sub CommandButton1_Click()
    'Process Controls collection for UserForm
    Set MyControl = Controls.Item(ControlsIndex)
    Set MyParent = MyControl.Parent
    Label1.Caption = MyControl.Name
    Label2.Caption = MyParent.Name
        
    'Prepare index for next control on Userform
    ControlsIndex = ControlsIndex + 1
    If ControlsIndex >= Controls.Count Then
        ControlsIndex = 0
    End If
End Sub