0

此请求基于 MS Access VBA。我想知道最有效的方法是什么,看看一个项目是否存在于列表框控件中。

4

3 回答 3

2

这是一个可以适应的示例函数。

Function CheckForItem(strItem, ListB As ListBox) As Boolean
Dim rs As DAO.Recordset
Dim db As Database
Dim tdf As TableDef

    Set db = CurrentDb

    CheckForItem = False

    Select Case ListB.RowSourceType
        Case "Value List"
            CheckForItem = InStr(ListB.RowSource, strItem) > 0

        Case "Table/Query"
            Set rs = db.OpenRecordset(ListB.RowSource)

            For i = 0 To rs.Fields.Count - 1
                strList = strList & " & "","" & " & rs.Fields(i).Name
            Next

            rs.FindFirst "Instr(" & Mid(strList, 10) & ",'" & strItem & "')>0"

            If Not rs.EOF Then CheckForItem = True

        Case "Field List"

            Set tdf = db.TableDefs(ListB.RowSource)

            For Each itm In tdf.Fields
                If itm.Name = strItem Then CheckForItem = True
            Next

    End Select

End Function
于 2008-09-19T23:14:06.453 回答
1

不幸的是,没有比线性搜索更有效的方法了,除非你知道你的列表框是以某种特定的方式排序或索引的。

For i = 1 To TheComboBoxControl.ListCount
  if TheComboBoxControl.ItemData(i) = "Item to search for" Then do_something()
Next i
于 2008-09-19T22:24:48.833 回答
1

如果您不介意使用 Windows API,您可以搜索如下字符串:

Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long   
Private Const LB_FINDSTRINGEXACT = &H1A2

Dim index as Integer
Dim searchString as String
searchString = "Target" & Chr(0)

index = SendMessage(ListBox1.hWnd, LB_FINDSTRINGEXACT , -1, searchString)

哪个应该返回包含目标字符串的行的索引。

于 2008-09-19T22:33:41.480 回答