我有一个访问数据库,我在VBA和ADODB的帮助下从excel搜索。
它工作得非常好,但我一次只能搜索一件事。假设我想要搜索"名字"的所有实例。在列[1]中也有"姓氏"在专栏[2]中。或者,"名字"在列[1]和"地址"在专栏[3]中。
我如何从用户表单上的文本框中执行此操作?
我在考虑以某种方式添加"名字+姓氏"什么的,但我无法弄清楚代码的逻辑。有什么建议吗?
这就是我现在所拥有的。
Private Sub cmd_lookup_Click()
Dim cn As Object
Dim rs As Object
Set cn = CreateObject("ADODB.Connection")
Set sqlConnect = New ADODB.Connection
Set rs = CreateObject("ADODB.RecordSet")
sqlConnect.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Source\database.accdb;Persist Security Info=False;"
cn.Open sqlConnect
rs.ActiveConnection = cn
SearchCriteria = "%" & searchCrit.Text & "%"
rs.Open "SELECT [1],[2] ,[3],[4], [5] FROM [tblDatabase]" & _
"WHERE [1] LIKE '" & SearchCriteria & "' " & _
" OR [2] LIKE '" & SearchCriteria & "' " & _
" OR [3] LIKE '" & SearchCriteria & "' " & _
" OR [4] LIKE '" & SearchCriteria & "' " & _
" OR [5] LIKE '" & SearchCriteria & "' " & _
"ORDER BY [2] Desc;", _
cn, adOpenStatic
Dim i As Integer
If Not rs.EOF Then
rs.MoveFirst
i = 0
With lstLookup
'Code not relevant
End With
rs.Close
cn.Close
Set rs = Nothing
Set cn = Nothing
End If
End Sub
感谢您的建议:)
答案 0 :(得分:0)
考虑由AND
运算符分隔的OR
个parings。但首先要使用单独的文本字段构建userform(并且每个必须是必填字段,否则必须动态构建WHERE
子句):
First Name Search:_____________
Last Name Search: _____________
Address Search: _______________
然后将标准绑定在一起。此外,出于调试原因,我不会建议编号但命名的字段:
rs.Open "SELECT [1], [2], [3], [4], [5]" & _
" FROM [tblDatabase]" & _
" WHERE ([1] LIKE '%" & FirstNameSearch & "%' " & _
" AND [2] LIKE '%" & LastNameSearch & "%') " & _
" OR ([1] LIKE '%" & FirstNameSearch & "%' " & _
" AND [3] LIKE '%" & AddressSearch & "%') " & _
" OR ([2] LIKE '%" & LastNameSearch & "%' " & _
" AND [3] LIKE '%" & AddressSearch & "%') " & _
" ORDER BY [2] Desc;", _
cn, adOpenStatic
或者,在SQL世界中经常使用UNION查询,讨论UNION vs OR之间的效率。要真正等效,应在上面添加DISTINCT
以删除重复项。
rs.Open "SELECT [1], [2], [3], [4], [5]" & _
" FROM [tblDatabase]" & _
" WHERE ([1] LIKE '%" & FirstNameSearch & "%' " & _
" AND [2] LIKE '%" & LastNameSearch & "%') " & _
" UNION" _
" SELECT [1], [2], [3], [4], [5]" & _
" FROM [tblDatabase]" & _
" WHERE ([1] LIKE '%" & FirstNameSearch & "%' " & _
" AND [3] LIKE '%" & AddressSearch & "%') " & _
" UNION" _
" SELECT [1], [2], [3], [4], [5]" & _
" FROM [tblDatabase]" & _
" WHERE ([2] LIKE '%" & LastNameSearch & "%' " & _
" AND [3] LIKE '%" & AddressSearch & "%') " & _
" ORDER BY [2] Desc;", _
cn, adOpenStatic