My Blog

Deselect Items in MultiSelect Listbox without looping

1

Consider this: Multiselect Listbox. I simply used the following code to generate it:

Private Sub UserForm_Initialize()
    For i = 1 To 100000
        ListBox1.AddItem i
    Next i
End Sub

Now imagine the following: I have some 50 entries selected and after my work is done, I would like to deselect them. The only options that I have are either I

  • 1) Manually unselect them OR…
  • 2) Write a code which will loop through the entries and deselect them like this?
For i = 1 To ListBox1.ListCount
    ListBox1.Selected(i - 1) = False
Next i

  • Right..?
  • Wrong! There is a third way.

I see two problems with the 2nd way:

  • 1) Looping takes time if Listbox contains huge data
  • 2) It causes a flicker if Listbox contains huge data

Here is an extraordinary way to do it, which I discovered it on my own. I quickly did a search on the web and couldn’t find a single website which suggested this:

Private Sub CommandButton1_Click()
    '~~> Reset selected items to deselected by changing it's selection behavior
    ListBox1.MultiSelect = fmMultiSelectSingle
    ListBox1.MultiSelect = fmMultiSelectMulti
End Sub

 

  1. Transformer
    Transformer06-28-2013

    Cool…another way to do that
    ListBox1.List = ListBox1.List