ms access 在 Dlookup 期间给出运行时错误 2471

问题描述

我有一个表单,允许用户向表中添加记录。我正在尝试添加一个按钮,允许他们将当前显示的记录复制到新记录。

我的代码是:

Private Sub Command1947_Click()
    Dim currentID As Long
 
    If IsNull(Panel_ID) Then
        MsgBox prompt:="Please select the record to copy first.",buttons:=vbExclamation
        Exit Sub
    End If
    
    currentID = Panel_ID
    DoCmd.GoToRecord record:=acNewRec
    
    
    MsgBox prompt:=DLookup("Job_Number","Table1","Panel_ID=" & currentID),buttons:=vbExclamation
    
    Job_Number = DLookup("Job_Number","Panel_ID=" & currentID)
    Date_of_MFG = DLookup("Date_of_MFG","Panel_ID=" & currentID)
    'Build_Hours = DLookup("Build_Hours","Panel_ID=" & currentID)
    Quality_Initials = DLookup("Quality_Initials","Panel_ID=" & currentID)
    Builders = DLookup("Builders","Panel_ID=" & currentID)
    'Shop_Location = DLookup("Shop_Location","Panel_ID=" & currentID)
    Customer_Name = DLookup("Customer_Name","Panel_ID=" & currentID)
    Customer_Part = DLookup("Customer_Part","Panel_ID=" & currentID)
    'Ship_First_Pass = DLookup("Ship_First_Pass","Panel_ID=" & currentID)
    LOM = DLookup("LOM","Panel_ID=" & currentID)
    'Prints_Red_Lined = DLookup("Prints_Red_Lined","Panel_ID=" & currentID)
    Quality_Touch_Points = DLookup("Quality_Touch_Points","Panel_ID=" & currentID)
    Spot_Checker_Initials = DLookup("Spot_Checker_Initials","Panel_ID=" & currentID)
    'Drawings_Highlighted = DLookup("Drawings_Highlighted","Panel_ID=" & currentID)
    
End Sub

面板 ID 是我的主键,是一个自动生成的序列号。 Table1 是包含数据的表的名称

当我运行代码时,构建时间、商店位置、发货第一次通过、打印红线和突出显示的图纸都给了我:

运行时错误“2471”:您作为查询参数输入的表达式产生了以下错误:“Build_Hours”

Error Image

Build hours 是一个十进制数,另外 4 个产生错误的都是短文本。代码似乎在表中找不到这些字段。

此外,当将产生错误的 5 个字段设置为注释并运行其余代码时,所有其他字段似乎只向新记录返回空值。

现在似乎只有 MsgBox 和从旧记录获取面板 ID 后移动到新记录是有效的部分。

我很久以前就学会了如何使用 Access,但从那以后它似乎发生了很大的变化,我基本上是在使用它并在谷歌搜索的帮助下重新学习它,所以请耐心等待我。

解决方法

我假设 Panel_ID 是数字类型。还假设控件与它们绑定到的字段具有相同的名称。

如果字段名称有空格而不是下划线,请用 is_legal_move 括起来。使用表单前缀来引用表单的字段和控件。 [ ] 可以在表单后面的代码中用作表单名称的别名。

Me

不要使用 DLookup 进行多次调用,而是执行一次调用以打开记录集对象并提取数据。

With Me
    currentID = .[Panel ID]
    DoCmd.GoToRecord record:=acNewRec
    .[Job Number] = DLookup("[Job Number]","Table1","[Panel ID]=" & currentID)
    ...
End With

或者,由于数据已经被绑定表单拉取:

Dim rs As DAO.Recordset
With Me
    Set rs = CurrentDb.OpenRecordset("SELECT * FROM Table1 WHERE [Panel ID] =" & .[Panel ID])
    DoCmd.GoToRecord record:=acNewRec
    .[Job Number] = rs![Job Number]
    ...
End With

强烈建议不要在命名约定中使用空格、标点符号/特殊字符或保留字作为名称。