查看项目是否在列表框控件中的最有效方法
时间:2020-03-06 14:28:00 来源:igfitidea点击:
该请求基于MS Access VBA。我想知道最有效的方法是什么,看看列表框控件中是否存在某个项目。
解决方案
不幸的是,没有比线性搜索更有效的方法,除非我们知道列表框是以某种特定方式排序或者索引的。
For i = 1 To TheComboBoxControl.ListCount if TheComboBoxControl.ItemData(i) = "Item to search for" Then do_something() Next i
如果我们不介意使用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)
哪个应该返回包含目标字符串的行的索引。
这是一个可能适合的示例函数。
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

