2

查看下面的以下代码行。

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

问题:如果 rst.FindFirst 表达式中的任何值为 Null,则 rst.NoMatch 始终返回 true,即使在正在评估的字段中存在具有匹配 Null 值的记录。这种行为是可以预期的还是可能存在另一个潜在问题。我检查了msdn页面,但它没有提供有关此类行为的信息。

4

2 回答 2

2

考虑一种不同的方法。请注意,这是针对一组文本数据类型字段。

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) 
于 2013-02-06T14:50:57.383 回答
1

当某个控件的值为 Null 时,您的.FindFirst 条件必须检查相应字段是否与Is Null控件的值相等而不是相等。从一个更简单的示例开始,检查两个控件/字段对。

Dim strCriteria As String
If IsNull(Me.Microwave) Then
    strCriteria = " AND Microwave Is Null"
Else
    strCriteria = " AND Microwave = '" & Me.Microwave & "'"
End If
If IsNull(Me.WashingMachine) Then
    strCriteria = strCriteria & " AND WashingMachine Is Null"
Else
    strCriteria = strCriteria & " AND WashingMachine = '" & Me.WashingMachine & "'"
End If
If Len(strCriteria) > 0 Then
    ' discard leading " AND "
    strCriteria = Mid(strCriteria, 6)
    Debug.Print strCriteria 
    rst.FindFirst strCriteria
End If
于 2013-02-06T15:45:15.153 回答