Excel VBA:根据文本框中设置的值在列表框中搜索值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26174823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 04:44:46  来源:igfitidea点击:

Excel VBA: Searching for value in listbox based on value set in textbox

excelvbaexcel-vbalistbox

提问by mario R.

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
  • SearchButton:一个按钮,点击后应该启动搜索
  • SearchBox:包含搜索值的文本框
  • AvailableNumberList:包含数据的列表框

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

采纳答案by Siddharth Rout

Is this what you are trying?

这是你正在尝试的吗?

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

Also use Exit Foronce a match is found :)

Exit For一旦找到匹配项,也可以使用:)