PDA

View Full Version : Solved: How to tell if no value is selected in a listbox



RECrerar
09-11-2007, 05:04 AM
Hi, I've had a search and can't find this.

I have a userform with two listboxes. Listbox2 is populated from a worksheet with values that depend on the value of listbox1. Listbox2 will sometimes be empty.

If listbox2 is not empty I need an error message displayed if nothing is selected.

The problem occurs if an item in listbox2 is selected and then the user selects a different value in listbox 1 which brings up a different set of values in listbox2. Even if none of the new values are selected my code refuses to believe that listbox2.value = "". Also the code sporadically desides not to work even if no value in listbox2 has ever been selected.

I'm not sure how well that is explained, so I've attached a workbook which you can look at

L@ja
09-11-2007, 05:11 AM
hali,

For i = 0 To Me.ListBox1.ListCount
If Me.ListBox1.Selected(i) = True Then
Exit For
End If
Next i
If i = Me.ListBox1.ListCount + 1 Then
MsgBox "you not selected anything..."
Exit Sub
End If

RECrerar
09-11-2007, 05:19 AM
Clever, I like it, thanks a lot L@ja, would never have thought of doing it that way.

Bob Phillips
09-11-2007, 05:33 AM
Check the ListIndex property, it is -1 for nothing selected.

RECrerar
09-11-2007, 05:33 AM
to add to the post myself:

If listbox2.listindex = -1 Then
msgbox "You have not selected anything....."
Exit Sub
End If


Also works

RECrerar
09-11-2007, 05:34 AM
ha ha, simultaneous replying! Yeah just found that

Bob Phillips
09-11-2007, 05:34 AM
As I just said ... but yiu might need a Then.

RECrerar
09-11-2007, 06:22 AM
oh yes, sorry typo, there is of course a Then in the code, have Edited it to be correct

lifeson
09-19-2007, 07:26 AM
Check the ListIndex property, it is -1 for nothing selected.

Is the listindex always -1?
I have this code:
Private Sub cmdSelect_Click()
Dim iItem As Double
Dim val As String
Dim id As String
If lstAcc.ListIndex = -1 Then
msg = "No item has been selected," & vbNewLine
msg = msg & "Select an item from the list to add"
ans = MsgBox(msg, vbExclamation)
Else
For iItem = 0 To lstAcc.ListCount - 1
If lstAcc.Selected(iItem) = True Then
id = lstAcc.list(iItem) ' identifies pack number
val = lstAcc.list(iItem) ' identifies pack description
If frmQty Is Nothing Then Set frmQty = New FrmAccQty
frmQty.SelectedValue = val
frmQty.Show
lstAcc.Selected(iItem) = False
End If
Next
End If
End Sub
And the message is not shown
The listindex appears to be 0 whether the first item or no item is selected.

Bob Phillips
09-19-2007, 07:43 AM
I just ran the code up and I got the error message as expected, that is it is -1

lifeson
09-19-2007, 08:01 AM
As this thread is marked solved I'll post my code in a new one