Search code examples
vbams-accesssearchfiltersubform

Using "Or" in Filter


I've a search button which when clicked shows the records in sub-form that match the values in text boxes in the parent form. And I have a radio button to choose between "And Search"(if matches all the criteria) and "Or Search"(if matches any one of the criteria). I'm using filter to show the result. This works perfectly for the "And Search" but not for "Or Search". When during "Or Search" all records despite any value in the text boxes are shown. My code is as below. Hoping to find a solution here. Thank You.

    Private Sub Form_Open(Cancel As Integer)

    Dim StrId, StrName, FilterId, FilterName, AndOr As String
    Dim IntRadio as Integer

    If Not IsNull(Forms!ParentForm!TxId.Value) Then
        StrId = Forms!ParentForm!TxId.Value
    End If

    FilterId = "[BookID] Like '*" & StrId & "*'"
    FilterName = "[BookName] Like '*" & StrName & "*'"

    If IntRadio = 1 Then
        AndOr = " and "
    Else
        AndOr = " or "
    End If

    Me.Filter = FilterId & AndOr & FilterName 
    Me.FilterOn = True
        Me.Requery

    If Me.RecordsetClone.RecordCount = 0 Then
        Cancel = True
        MsgBox "No Records", vbOKOnly + vbInformation, "No Data"
    End If

End Sub

Solution

  • Private Sub Form_Open(Cancel As Integer)
    
    Dim StrId, StrName, StrFilter, AndOr As String
    Dim IntRadio as Integer
    
    If IntRadio = 1 Then
        AndOr = " and "
    Else
        AndOr = " or "
    End If
    
    If Not IsNull(Forms!ParentForm!TxId.Value) Then
        StrId = Forms!ParentForm!TxId.Value
        StrFilter = StrFilter & "[BookID] Like '*" & StrId & "*'" & AndOr
    End If
    
    If Not IsNull(Forms!ParentForm!TxName.Value) Then
        StrId = Forms!ParentForm!TxName.Value
        StrFilter = StrFilter & "[BookName] Like '*" & StrName & "*'" & AndOr
    End If  
    
    StrFilter = Left(StrFilter, Len(StrFilter) - 4)
    
    Me.Filter = StrFilter
    
    Me.FilterOn = True
    Me.Requery
    
    If Me.RecordsetClone.RecordCount = 0 Then
        Cancel = True
        MsgBox "No Records", vbOKOnly + vbInformation, "No Data"
    End If
    End Sub