当 table 中的字段为 Null 时,DLookup 和 Nz() 的格式是什么?

What is the DLookup and Nz() format for when field in table is Null?

我有一个从 MyTable 中获取 [Model] 的 DLookup 公式。一切正常,直到字段名 [Model] 的值为空。

我收到运行时错误 94,说明它不理解空信息。

我试过使用 Nz() 函数。当我有这么多双引号和单引号时,使用这些函数会很混乱。

这就是我的。

Dim other as String
other = DLookup("[Model]", "[Part Number & Part Name]", "[Part Number]='" & Forms![Press 2]![Containment - Press 2 subform].Form![Part Number] & "'")

If other <> "" Then
    Me.[Model].Value = other
Else
    Me.Model.Value = "NA"
End If

您的代码中空值有两个棘手的地方:

  1. 如果 Forms![Press 2]![Containment - Press 2 subform].Form![Part Number] 为 null,则 DLookUp 将被错误处理,因为您将其作为字符串包含在内。

    修复:使用表单值作为参数,这也避免了SQL注入错误:

    other = DLookup("[Model]", "[Part Number & Part Name]", "[Part Number]= Forms![Press 2]![Containment - Press 2 subform].Form![Part Number]")
    
  2. 您正在将 DLookUp 结果存储在一个字符串中。您可以在此处使用 Nz 来 return 不同的字符串,或者将零长度字符串与 DLookUp 结果连接起来以将 Null 值处理为零长度字符串:

    other = VbNullString & DLookup("[Model]", "[Part Number & Part Name]", "[Part Number]= Forms![Press 2]![Containment - Press 2 subform].Form![Part Number]")
    

这应该涵盖空值可能会干扰这部分代码的所有地方。

使用Nz并减少代码:

Dim other as String

other = Nz(DLookup("[Model]", "[Part Number & Part Name]", "[Part Number]='" & Forms![Press 2]![Containment - Press 2 subform].Form![Part Number] & "'"), "NA")   
Me![Model].Value = other