Deselect Items in MultiSelect Listbox without looping


EDIT

I have stopped updating this blog. This link can also be found in my Website.

http://www.siddharthrout.com/2011/07/29/deselect-items-in-multiselect-listbox-without-looping/

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

MultiSelect Listbox

Now imagine, 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. I just 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

Hope this helps 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: