此请求基于MS Access VBA。我想知道最有效的方法是查看列表框控件中是否存在项目。
答案 0 :(得分: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
答案 1 :(得分:1)
不幸的是,没有比线性搜索更有效的方法,除非你知道你的列表框是以某种特定方式排序或索引的。
For i = 1 To TheComboBoxControl.ListCount
if TheComboBoxControl.ItemData(i) = "Item to search for" Then do_something()
Next i
答案 2 :(得分: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)
哪个应该返回包含目标字符串的行的索引。