感谢 Vlado,您的回答鼓舞人心,简洁且带有 gif 说明。几天前,一位要求严格的客户要求我提供相同的功能。
但是,请求是进行类似 google 的搜索。换句话说,允许在目标组合中随机(在您键入时)搜索 [部分地] 包含多个短语(当然是 ANDed)。文本(这是多个“标签”字段的串联,包括鸡尾酒名称、酒精(Y/N)、成分、玻璃器皿、品牌、类别......等。
现在我又被问到同样的问题。我想把它附在这里以供将来搜索以帮助其他人(被困的程序员)。再次感谢弗拉多。
给你:
Public Sub GoogleSearch(combo As ComboBox, OriginalSQL As String, LookupField As String)
' - OriginalSQL is not the recursive one
' - Use queries to build up your sql statement, then copy/paste thier sql text in the combo row source
' do not just point the row source to the query name (keep the query for reference if you like.
' to avoid the quotation agony of VBA built-in editor to create your OriginalSQL
' - Always store your OriginalSQL in global module variable,
' - Initiate it on (form) load, restore it on cancel AND after_update
' Created by Walid Zohair, not to be used without the exact comments
If Trim(combo.Text) = "" Or IsNull(combo.Text) Then
combo.RowSource = OriginalSQL
combo.Requery
combo.Dropdown
combo.SetFocus
Exit Sub
End If
Dim SQLStr As String
SQLStr = Replace(OriginalSQL, ";", "") ' make sure a bar end sql is used
' make sure order_by, group_by, Having will not be after where clause (gives error)
' This also can be used to give clearer names in outer SQL to be used in Where clause later
SQLStr = "SELECT * FROM ( " & SQLStr & " ) WHERE "
Dim StrArray() As String
StrArray = Split(Trim(combo.Text)) ' for saftey could be limited to up to 100 records only = Split(combo.text, " ", 100)
For i = 0 To UBound(StrArray)
SQLStr = SQLStr & LookupField & " LIKE '*" & StrArray(i) & "*'"
If UBound(StrArray) - i > 0 Then
SQLStr = SQLStr & " AND " ' Add AND to the search string
End If
Next i
combo.RowSource = SQLStr
combo.Dropdown
End Sub
此外,根据 SO 社区指南,我相信这可以更多地考虑到问题(更好的答案),而不是对其他答案的反应。