Question : Determining if items are selected in a listbox

I have a listbox on a form user's can use to generate a report. The listbox contains fields to be included on the report. To make sure the user has selected at least one item I use:
If lstIncludedFields.ListIndex <> -1 Then

However, I also have a Select All button to save the users time. The code for this button is below. The button caption toggles back and forth between Select All and Deselect All and has reverse actions.

The problem I am having is that when the user just uses the Select All the ListIndex = -1, so my check fails and the user is told to select at least one field. I have tried setting the ListIndex property myself but I get an error. I also tried to requery the listbox but the listindex property stays at -1.
Code Snippet:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
Private Sub cmdSelectAllFields_Click()
Dim intIndex As Integer
 
    intIndex = 0
    Do While intIndex < lstIncludedFields.ListCount
        lstIncludedFields.Selected(intIndex) = (cmdSelectAllFields.Caption = "Select All")
    
        intIndex = intIndex + 1
    Loop
 
    If cmdSelectAllFields.Caption = "Select All" Then
        cmdSelectAllFields.Caption = "Deselect All"
    Else
        cmdSelectAllFields.Caption = "Select All"
    End If
    
    'lstIncludedFields.ListIndex = lstIncludedFields.ListCount - 1
    lstIncludedFields.Requery
End Sub
Open in New Window Select All

Answer : Determining if items are selected in a listbox

You can use the ItemsSelected property:

If Me.lngIncludedFields.ItemsSelected.Count > 0 then

End If
Random Solutions  
 
programming4us programming4us