Consulting

Results 1 to 4 of 4

Thread: Was a specific item selected in a multi-select listbox?

  1. #1
    VBAX Mentor clhare's Avatar
    Joined
    Mar 2005
    Posts
    470
    Location

    Was a specific item selected in a multi-select listbox?

    Hi all! I have a multi-select listbox with 5 items in it on my userform. If one specific item is selected, I need to do something. How do I check to see if that item is selected?

    I tried adding the following to the click event for the listbox, but it only works if the box is single-select.

    HTML Code:
    Private Sub lstMyListbox_Click() 
    With lstMyListbox
        If .Selected(2) Then
            MsgBox "you selected item B"
        End If
    End With
    
    End Sub
    Thanks!

    Cheryl

  2. #2
    Moderator VBAX Sage SamT's Avatar
    Joined
    Oct 2006
    Location
    Near Columbia
    Posts
    7,814
    Location
    For a Multiselect control you need to look at each index to see if it is Selected.

    This is just example code, It doesn't actually fit your requirements.
    Private Sub LBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    Dim i
    Dim j
    Dim SelectionList(lbox1.ListCount) 'an array of selected Items
    Dim Selections As String 'A comma separated String of Selected Items
    
     For i = -1 To lbox1.ListCount - 1
     'List indexes start at zero, Counts start at 1, Listindex -1 means no item selected.
     
      If lbox1(i).Selected Then
       SelectionList(j) = lbox1(i)
       j = j + 1
       
       If i = -1 Then
         Selections = "False"
       Else
         Selections = Selections & ", " & lbox1(i)
       End If
      End If
      
     Next i
    End Sub
    I expect the student to do their homework and find all the errrors I leeve in.


    Please take the time to read the Forum FAQ

  3. #3
    Microsoft Word MVP 2003-2009 VBAX Guru gmaxey's Avatar
    Joined
    Sep 2005
    Posts
    3,340
    Location
    Cheryl,
    The click event isn't triggered with a multi-select listbox (Since list items are indexed from 0 you may need to change (2) to (1):

    Private Sub lstMyListbox_Change()
        If lstMyListbox.Selected(2) Then Msgbox "You selected item B"
    End Sub
    Greg

    Visit my website: http://gregmaxey.com

  4. #4
    VBAX Mentor clhare's Avatar
    Joined
    Mar 2005
    Posts
    470
    Location
    Thank you! That works perfectly!

    Cheryl

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •