在多个列中search
我有一个访问数据库,我从Excel中通过VBA和ADODB的帮助search。
它工作得很好,但是我一次只能search一件东西。 假设我想search列[1]中“first name”的所有实例,列[2]中也有“last name”。 或者,列[1]中的“名”和列[3]中的“地址”。
我将如何去做一个用户表单上的文本框?
我想在某种程度上添加“名字+姓氏”或其他东西,但我无法弄清代码的逻辑。 有什么build议么?
这是我现在所拥有的。
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
感谢您的build议:)
考虑由OR
运算符分隔的AND
分隔符。 但首先有用户窗体结构与单独的文本字段(每个必须是必填字段,否则您必须dynamic地build立WHERE
子句):
First Name Search:_____________ Last Name Search: _____________ Address Search: _______________
然后将标准绑定在一起。 此外,我不会build议数字,但命名字段出于debugging的原因:
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与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