为什么 ListBox 在 Excel-VBA 中没有 FindString 方法?

Why ListBox doesn't have a FindString method in Excel-VBA?

正在尝试搜索列表框。具体来说,我想查看 Cell 中的一组项目,对于每个与 ​​ListBox 中的条目匹配的项目,我希望它 select 该列表。 我复制粘贴了一些本应让我找到字符串的代码,但它一直告诉我:

Compile Error: Method or Data Member not found.

有什么建议吗?

相关代码:

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 并不真正支持它,但无论如何,您可以创建一个函数来做到这一点。如下所示。

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
    End If
    SearchString = -1
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

我并不是说我上面创建的函数是最有效的方法。
这只是一个示例,旨在为您提供解决方法的想法。 HTH.

重要提示: 这适用于具有一维数组列表的单列列表框。如果您需要处理多列列表框,则必须稍微调整一下函数。