Il modo più efficiente per vedere se un elemento è o meno in un controllo della casella di riepilogo
-
01-07-2019 - |
Domanda
Questa richiesta è basata su MS Access VBA. Vorrei sapere qual è il modo più efficiente, per vedere se esiste un elemento in un controllo listbox.
Soluzione
Ecco una funzione di esempio che potrebbe essere adattata per adattarsi.
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
Altri suggerimenti
Sfortunatamente non esiste un modo più efficiente di una ricerca lineare, a meno che tu non sappia che la tua casella di riepilogo è ordinata o indicizzata in un modo particolare.
For i = 1 To TheComboBoxControl.ListCount
if TheComboBoxControl.ItemData(i) = "Item to search for" Then do_something()
Next i
Se non ti dispiace ricorrere all'API di Windows puoi cercare una stringa come questa:
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)
Che dovrebbe restituire l'indice della riga che contiene la stringa di destinazione.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow