为什么ListBox在Excel-VBA中没有FindString方法?
试图在ListBox上search。 具体来说,我想查看一个单元格中的项目数组,并为每个匹配列表框中的条目,我希望它select该列表。 我复制了一些应该让我find一个string的代码,但它一直告诉我:
编译错误:找不到方法或数据成员。
有什么build议么?
相关编码:
Public local_Target As Range ' local_Target is assigned in the sheet function to pass it here Private Sub Network_ListBox_Enter() ' Get data in cell (if any) Dim current_data As String Dim entries() As String current_data = local_Target.Value If current_data = "" Then Exit Sub Else entries = Split(current_data, vbNewLine) End If For Each Item In entries FindMyString Item Next Item End Sub Private Sub UserForm_Terminate() Dim index As Integer Dim result As String ' Iterate through the listbox and create the result, then assign to ' Target.value For index = 0 To Network_ListBox.ListCount - 1 If Network_ListBox.Selected(index) Then ' stuff If result = "" Then result = Network_ListBox.List(index) ' ElseIf index = Network_ListBox.ListCount - 1 Then ' result = result + Network_ListBox.List(index) Else result = result + vbNewLine + Network_ListBox.List(index) End If End If Next index local_Target.Value = result End Sub Sub FindMyString(ByVal searchString As String) ' Ensure we have a proper string to search for. If searchString <> "" Then ' Find the item in the list and store the index to the item. Dim index As Integer index = Me.Network_ListBox.FindString(searchString) ' Determine if a valid index is returned. Select the item if it is valid. If index <> -1 Then Network_ListBox.SetSelected index, True 'Else ' MessageBox.Show ("The search string did not match any items in the ListBox") End If End If End Sub
我检查了Intellisense
,我不认为在VBA中支持Method
。
我发现的其他文档也只提及.Net Framework
。
所以也许,在VBA中它并不是真的被支持,但是无论如何,你可以创build一个函数来做到这一点。 像下面的东西。
Private Function SearchString(mysearch As String, mylist As Variant) As Long Dim itm As Variant, idx As Long: idx = 0 If IsArray(mylist) Then For Each itm In mylist If mysearch = itm Then SearchString = idx: Exit Function End If idx = idx + 1 Next SearchString = -1 End If End Function
你可以像这样使用它:
Private Sub CommandButton1_Click() Dim i As Long 'do the search i = SearchString("WhatImSearching", Me.ListBox1.List) 'select the item that match your search If i <> -1 Then Me.ListBox1.Selected(i) = True End Sub
我并不是说我上面创build的函数是最有效的方法。
这只是一个例子,给你一个解决方法的想法。 HTH。
重要提示:这适用于具有一维数组列表的单列列表框。 如果你需要在多列ListBox上工作,你将不得不稍微调整一下这个函数。