Microsoft Access: VBA Programming Code

Provided by Allen Browne, June 2006


ClearList() and SelectAll() functions

The ClearList() function deselects all items in a multi-select list box, or sets the value to Null if the list box is not multi-select.

The SelectAll() function selects all the items in a multi-select list box. It has no effect is the list box is not multi-select.

Use your own error logger, or copy the one in this link: LogError()

Examples:

  1. To select all items in the list box named List0 on Form1:
        Call SelectAll(Forms!Form1!List0)
  2. To deselect them all:
        Call ClearList(Forms!Form1!List0)

The code


Function ClearList(lst As ListBox) As Boolean
On Error GoTo Err_ClearList
    'Purpose:   Unselect all items in the listbox.
    'Return:    True if successful
    'Author:    Allen Browne. http://allenbrowne.com  June, 2006.
    Dim varItem As Variant

    If lst.MultiSelect = 0 Then
        lst = Null
    Else
        For Each varItem In lst.ItemsSelected
            lst.Selected(varItem) = False
        Next
    End If

    ClearList = True

Exit_ClearList:
    Exit Function

Err_ClearList:
    Call LogError(Err.Number, Err.Description, "ClearList()")
    Resume Exit_ClearList
End Function

Public Function SelectAll(lst As ListBox) As Boolean
On Error GoTo Err_Handler
    'Purpose:   Select all items in the multi-select list box.
    'Return:    True if successful
    'Author:    Allen Browne. http://allenbrowne.com  June, 2006.
    Dim lngRow As Long

    If lst.MultiSelect Then
        For lngRow = 0 To lst.ListCount - 1
            lst.Selected(lngRow) = True
        Next
        SelectAll = True
    End If

Exit_Handler:
    Exit Function

Err_Handler:
    Call LogError(Err.Number, Err.Description, "SelectAll()")
    Resume Exit_Handler
End Function

HomeIndex of tipsTop