Select a value in Listbox and set focus over that value - VBA

I am trying to select a value in Listbox dynamically. But am not able to do so. I am getting an error, Object doesn't support this property or method.

Here is the code,

ReqSearchvalue = Range("B" & reqrow).Value

Sheets("Main").Activate

With Sheets("Main").Ent_ListBox
    .Values = ReqSearchvalue
    .SetFocus = ReqSearchvalue
End With

Kindly share your thoughts. Thanks in advance !

Upvotes: 0

Views: 11825

Answers (2)

Kostas K.
Kostas K.

Reputation: 8518

Credit to @Peh for correcting this.

Loop through the List to find the index of the value you're looking and then set the .Selected(idx) to True.

Dim i As Long, found As Boolean
With Worksheets("Main").OLEObjects("Ent_ListBox").Object
    For i = 0 To .ListCount - 1
        If .List(i) = ReqSearchvalue Then
            found = True
            Exit For
        End If
    Next i
    If found then .Selected(i) = True
End With

Upvotes: 3

avb
avb

Reputation: 1753

ListBox.SetFocus is a method, it sets the focus on listbox itself, you cannot assign value to it. You must find desired item's index and use .SelectedItem(index) then.

Upvotes: -1

Related Questions