問題描述
查看項目是否在列錶框控件中的最有效方法 (Most efficient way to see if an item is or is not in a listbox control)
此請求基於 MS Access VBA。我想知道最有效的方法是什麼,看看某個項目是否存在於列錶框控件中。
參考解法
方法 1:
Here is a sample function that might be adapted to suit.
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
方法 2:
Unfortunately there is no more efficient way than a linear search, unless you know that your listbox is sorted or indexed in some particular fashion.
For i = 1 To TheComboBoxControl.ListCount
if TheComboBoxControl.ItemData(i) = "Item to search for" Then do_something()
Next i
方法 3:
If you don't mind resorting to the Windows API you can search for a string like this:
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)
Which should return the index of the row that contains the target string.
(by Curtis Inderwiesche、Fionnuala、Sparr、Rikalous)