ms-accessduplicatesvbafindfirst

Unexpected behaviour with .FindFirst VBA MS Access function: .NoMatch always returns true


View the following lines of code below.

Dim rst As DAO.Recordset
Dim strSql As String

strSql = "SELECT * FROM MachineSettingsT;"
Set rst = DBEngine(0)(0).OpenRecordset(strSql)

rst.FindFirst "Microwave = " & "'" & Me.Microwave & "'" & " AND WashingMachine =" & "'" & Me.WashingMachine & "'" & " AND Element1 =" & "'" & Me.Element1 & "'" _
               & "AND Element3 =" & "'" & Me.Element3 & "'" & "AND Dryer =" & "'" & Me.Dryer & "'" & "AND SettingID <>" & "'" & Me.SettingID & "'"

If Not rst.NoMatch Then  
    Cancel = True
    If MsgBox("Setting already exists; go to existing record?", vbYesNo) = vbYes Then
        Me.Undo
        DoCmd.SearchForRecord , , acFirst, "[SettingID] = " & rst("SettingID")
    End If
End If
rst.Close

Problem: If any of the values in the rst.FindFirst expression are Null then rst.NoMatch always returns true even when there is a record with a matching Null value in the field being evaluated. Is this behaviour to be expected or could there be another underlying problem. I checked the msdn page but it did not provide information about this sort of behaviour.


Solution

  • Consider a different approach. Note that this is for a set of text data type fields.

    Dim rst As DAO.Recordset
    Dim strSql As String
    Dim db As Database
    
    Set db=CurrentDB
    
    strSql = "SELECT * FROM MachineSettingsT WHERE 1=1 "
    ''Set rst = db.OpenRecordset(strSql)
    
    If not IsNull(Me.Microwave) Then
       strWhere =  " AND Microwave = '" & Me.Microwave & "'" 
    End if
    If not IsNull(Me.WashingMachine) Then
       strWhere = strWhere & " AND WashingMachine ='" & Me.WashingMachine & "'"
    End if
    If not IsNull(Me.Element1) Then
       strWhere = strWhere & " AND Element1 ='" & Me.Element1 & "'" 
    End if
    If not IsNull(Me.Element3) Then
       strWhere = strWhere & " AND Element3 ='" & Me.Element3 & "'"  
    End if
    If not IsNull(Me.Dryer) Then
       strWhere = strWhere & " AND Dryer ='" & Me.Dryer & "'"
    End if
    
    Set rst = db.OpenRecordset(strSql & strWhere)