PDA

View Full Version : Check no selection in a listbox..



hardwired
04-03-2008, 02:24 AM
Hi,

I know that this is a simple one but i'm simple, so help me, lol..

I want to trap error for if nothing has been selected in a listbox (its set to multiselect btw, just in case that matters)..

I tried this:






If LayoutLIST.ListIndex = -1 Then

MsgBox "No, its not selected"
Exit Sub
End If





...as a test but it didn't seem to work (saw that code somewhere online - not the msgbox bit)..

I know that the listbox in VBA is an MSForms listbox not a native VB one, so has different properties and all the info i've found online on how to do this doesn't work, so was wondering if someone on here knew what to do..

lucas
04-03-2008, 10:55 AM
Hi Paul,
Is this for excel or word?

Try this instead of -1
If LayoutLIST.ListIndex = 0 Then

rocheey
05-05-2008, 02:45 PM
BTW, if your listbox *is* coming back with a listindex of '0', with nothing selected, then you probably have the listbox set as multiselect style.

If thats what you are looking for (giving the users the ability to select none, one, or more than one selection) then the listindex is not a reliable method to check - the listindex will return only one number, even if more than one item is selected!

To check for selections in a multiselect, you have to loop thru the items in the listbox, checking each with the lisbox.selected property.

If you are only wanting to allow one selection in the listbox, set the liststyle to '0', and set your listindex to a default value at the start of your code, when you create the listbox. Since you cannot *unselect* all items when liststyle=0, you will *always* have a valid listindex of > -1.