Deselect Listbox

With Multi-select ListBoxes, you can use the Selected property to determine which items have been selected. You can also use Selected to select or deselect items via code. This post describes how to deselect all or a portion of the items in a ListBox.

The Selected property is an array with the same number of elements as there are items in a ListBox. It returns True if an item is selected and False if it isn’t. Setting this property to True or False will select or deselect an item, respectively. For this example, I’ve created a userform and added the numbers 1 through 10 to ListBox1. There are also two commandbuttons name cmdAll and cmdOdd. cmdAll will deselect every item in ListBox1 while cmdOdd will only deselect an item if it is an odd number. Here’s what my userform looks like:

Deselect1

The code for these commandbuttons is below.

Private Sub cmdAll_Click()
Dim i As Long
For i = 0 To Me.ListBox1.ListCount - 1
Me.ListBox1.Selected(i) = False
Next i
End Sub

Private Sub cmdOdds_Click()
Dim i As Long

With Me.ListBox1
For i = 0 To .ListCount - 1
If .List(i) Mod 2 = 1 Then
.Selected(i) = False
End If
Next i
End With
End Sub

In cmdAll_Click, the code simply loops through every item in ListBox1 and sets Selected to False. In cmdOdd_Click, however, the code tests the entry to see if it’s odd using the Mod operator. If it is, it deselects it in the same manner. Note that I don’t test the Selected property first. I don’t care if it’s already unselected because setting Selected to False will have no effect in that case.

2 thoughts on “Deselect Listbox

  1. I’d rather prefer multi-usable buttons.

    Private Sub cmdAll_Click()
      With ListBox1
      For i = 0 To .ListCount – 1
        .Selected(i) = Not .Selected(i)
      Next
      cmdAll.Caption=iif(.Selected(0),“Un”,“”) & “select All”
    End Sub

    Private Sub cmdOdds_Click()
      With Me.ListBox1
        For i = 0 To .ListCount – 1
          If .List(i Mod 2) = 1 Then .Selected(i) = not .selected(i)
        Next
      End With
      cmdOdds.Caption=iif(.Selected(1),“Un”,“”) & “select Odds”  
    End Sub

    A suggestion to fill the listbox elegantly and fast:
    Private Sub Userform_Initialize()
    Listbox1.List=split("1|2|3|4|5|6|7|8|9|10|11|12","|")
    End Sub

Leave a Reply

Your email address will not be published. Required fields are marked *