Search code examples
vbams-accesslistboxms-access-2010listboxitem

How to Select the entered values from the Multiselect listbox using vba code


I have a Textbox and a MultiSelect listbox with following values

enter image description here

When i enter the values in the text box and click on search it should select the particular values in the listbox. I'm Using the below code

Private Sub Search_Click()
Dim str As String
Dim c As Collection
Dim strArray() As String
Dim intcnt As Integer

str = txtAnswer.Value
strArray = Split(str, ",")

For Each itm In strArray
lstAnswer.Selected (itm)= True
Next
End Sub

I want to get the below result

enter image description here

But It selects the index instead of values. for Example

enter image description here

How to select the values instead of index?


Solution

  • Private Sub Search_Click()
    Dim ItM As String
    Dim c As Collection
    Dim strArray() As String
    Dim intcnt As Integer
    
    
    strArray = Split(txtAnswer.Value, ",")
    
    With lstAnswer
        For Each ItM In strArray
            For i = 0 To .ListCount - 1
                If .List(i) <> ItM Then
                Else
                    .Selected(i) = True
                    Exit For
                End If
            Next i
        Next ItM
    End With
    
    End Sub