2

I am trying to write a code for a search button which searches a listbox based a specific input set in a textbox. The values searched are always numbers, and the listbox contains values from a single column. The code i wrote can be found below but i don't understand why it is not functional.

Legend:

  • SearchButton: A Button which upon clicking is supposed to initiate the search
  • SearchBox: The textbox which will contain the search value
  • AvailableNumberList: The listbox which contains the data

Thanks for your help :)

Private Sub SearchButton_Click()
Dim SearchCriteria, i, n As Double
SearchCriteria = Me.SearchBox.Value
n = AvailableNumberList.ListCount
For i = 0 To n - 1
If SearchCriteria = i Then
AvailableNumberList.ListIndex = i
End If
Next i
End Sub

2 Answers 2

2

Is this what you are trying?

'If SearchCriteria = i Then
If AvailableNumberList.List(i) = SearchCriteria Then

Also use Exit For once a match is found :)

Sign up to request clarification or add additional context in comments.

2 Comments

(I'm kind of a noob in coding so I haven't used the "Exit for" previously) could you please point out where i should set that? Thanks :)
after the line AvailableNumberList.ListIndex = i
1

Additional to @Siddharth Rout solution, this code allows to search in the ListBox even if the TextBox does not have the full word/number:

Private Sub SearchButton_Click()

Dim SearchCriteria, i, n As Double
SearchCriteria = Me.SearchBox.Value
n = AvailableNumberList.ListCount

For i = 0 To n - 1
If Left(AvailableNumberList.List(i),Len(SearchCriteria))=SearchCriteria Then
AvailableNumberList.ListIndex = i
Exit For
End If
Next i

End Sub

Thanks everyone for their code! =D

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.