A collection whose elements represent each control on a form.
object.Controls(index)
The parts of the Controls collection syntax are described in the following table.
Part | Description |
---|---|
object | An object expression that evaluates to a Form object. |
Index | An integer with a range from 0 to the number of Controls - 1. |
The Controls collection enumerates loaded controls on a form and is useful for iterating through them. The Controls collection identifies an intrinsic form-level variable named Controls. If you omit the optional object placeholder, you must include the Controls keyword. However, if you include object, you can omit the Controls keyword.
Add a ListBox control named List1 to a form named Form1. Add several other controls to Form1. Add the following code to Form1, run the program, and click on the form (not on a control). The names of the controls on Form1 will be displayed in List1.
Private Sub Form_Click()
Dim ExitFlag, Index
ExitFlag = False
Index = 0
On Error Resume Next
Do
List1.AddItem Form1.Controls(Index).Name
'List1.AddItem Form1(Index).Name 'will also work.
If Err.Number = 0 Then
Index = Index + 1
Else
ExitFlag = True
End If
Loop Until ExitFlag
End Sub