AddItem Method

Applies To

ComboBox control, ListBox control.

Description

For a single-column list box or combo box, adds an item to the list. For a multicolumn list box or combo box, adds a row to the list.

Syntax

Variant = object.AddItem( [ item [, varIndex]])

The AddItem method syntax has these parts:

Part

Description

object

Required. A valid object.

Item

Optional. Specifies the item or row to add. The number of the first item or row is 0; the number of the second item or row is 1, and so on.

varIndex

Optional. Integer specifying the position within the object where the new item or row is placed.


Remarks

If you supply a valid value for varIndex, the AddItem method places the item or row at that position within the list. If you omit varIndex, the method adds the item or row at the end of the list.

The value of varIndex must not be greater than the value of the ListCount property.

For a multicolumn ListBox or ComboBox, AddItem inserts an entire row, that is, it inserts an item for each column of the control. To assign values to an item beyond the first column, use the List or Column property and specify the row and column of the item.

If the control is bound to data, the AddItem method fails.

Note You can add more than one row at a time to a ComboBox or ListBox by using List.

See Also

Column property, List property, ListCount property.

Example

The following example adds and deletes the contents of a ListBox using the AddItem, RemoveItem, and SetFocus methods, and the ListIndex and ListCount properties.

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

  • A ListBox named ListBox1.
  • Two CommandButton controls named CommandButton1 and CommandButton2.
    Dim EntryCount As Single
    Private Sub CommandButton1_Click()
        EntryCount = EntryCount + 1
        ListBox1.AddItem (EntryCount & " - Selection")
    End Sub
    
    Private Sub CommandButton2_Click()
        ListBox1.SetFocus
    
        'Ensure ListBox contains list items.
        If ListBox1.ListCount >= 1 Then
            'If no selection, choose last list item.
            If ListBox1.ListIndex = -1 Then
                ListBox1.ListIndex = ListBox1.ListCount - 1
            End If
            ListBox1.RemoveItem (ListBox1.ListIndex)
        End If
    End Sub
    
    Private Sub UserForm_Initialize()
        EntryCount = 0
        CommandButton1.Caption = "Add Item"
        CommandButton2.Caption = "Remove Item"
    End Sub