创建一个表单以根据多个条件搜索记录

Creating a form to search for records based on multiple criteria

我正在尝试创建一个允许您return 基于多个条件的结果的表单。

我有 FirstName 字段、LastName 字段和 State 字段。

我还有一个名为 searchFirstsearchLastsearchState 的文本框,用户可以在其中输入条件。

点击搜索按钮后会执行以下代码。

Private Sub mySearchQuery_Click()

Dim filter As String

Dim rtFirstName As String
Dim rtLastName As String
Dim rtState As String

rtFirstName = Me.searchFirst.Value
rtLastName = Me.searchLast.Value
rtState = Me.searchState.Value

If Not IsNull(rtFirstName) Then
        If Not IsNull(filter) Then filter = filter & " AND "
        filter = filter & "(FirstName like""*" & rtFirstName & "*"")"
End If


If Not IsNull(rtLastName) Then
        If Not IsNull(filter) Then filter = filter & " AND "
        filter = filter & "(LastName like""*" & rtLastName & "*"")"
End If

If Not IsNull(rtState) Then
        If Not IsNull(filter) Then filter = filter & " AND "
        filter = filter & "(State LIKE""*" & rtState & "*"")"
End If

' Now re-construct the SQL query '
Dim sql As String
sql = "SELECT * FROM MainData"

If Not IsNull(filter) Then
        sql = sql & " WHERE " & filter
End If

Me.RecordSource = sql
'SubForm.Form.RecordSource = sql

End Sub

我在下面收到以下错误。

Run-time error '3075': Syntax error (missing operator) in query expression 'AND (FirstName like"*tracy*") AND (lastName like"*Smith*") AND (State LIKE"*ga*")'.

我不确定为什么 AND 包含在搜索查询的开头?

I am not sure why AND was included at the beginning of the search query?

因为你有 Dim filter As Stringfilter 永远不能包含 Null。这意味着这些 If 条件... If Not IsNull(filter) ... 将永远为真。

同样,Not IsNull(rtFirstName)Not IsNull(rtLastName)Not IsNull(rtState) 将始终为 True。

最终结果是代码向您的 filter 字符串添加了另一个条件片段,无论相应的搜索文本框是否包含任何内容,并且每个片段都以 " AND " 为前缀。

考虑到这些要点,您可以重构代码,仅当相应的搜索文本框中有内容时才添加 filter 段,并决定何时包含 " AND "。然而,我发现为它们中的每一个都包含 " AND " 然后在将它添加到 WHERE 子句之前从 filter 中删除第一个 " AND " 更简单。

Private Sub mySearchQuery_Click()
    Dim strSelect As String
    Dim strWhere As String

    If Len(Trim(Me!searchFirst.Value) & vbNullString) > 0 Then
        strWhere = strWhere & " AND FirstName Like ""*" & Me!searchFirst.Value & "*"""
    End If

    If Len(Trim(Me!searchLast.Value) & vbNullString) > 0 Then
        strWhere = strWhere & " AND LastName Like ""*" & Me!searchLast.Value & "*"""
    End If

    If Len(Trim(Me!searchState.Value) & vbNullString) > 0 Then
        strWhere = strWhere & " AND State Like ""*" & Me!searchState.Value & "*"""
    End If

    ' Now re-construct the SQL query
    strSelect = "SELECT * FROM MainData"

    ' only add WHERE clause if we have something in strWhere    
    If Len(strWhere) > 0 Then
        ' use Mid() to ignore leading " AND "
        strSelect = strSelect & " WHERE " & Mid(strWhere, 6)
    End If
    Debug.Print strSelect ' <- inspect this in Immediate window; Ctrl+g will take you there

    ' enable one of these RecordSource lines after confirming Debug.Print shows you what you need
    'Me.RecordSource = sql
    'SubForm.Form.RecordSource = sql
End Sub