【发布时间】:2017-07-10 16:27:56
【问题描述】:
我正在尝试创建一个用于在某些情况下手动输入数据的表单。大多数数据是从运行良好的 CSV 文件输入的。我有 4 张桌子,Part、Assembly、MachineOrder 和 Job。我能够编写代码以从表单输入基表Part,这没问题。现在的问题是将数据输入到Assembly 和MachineOrder 表中,其中PID 自动编号字段引用了部件,AID 自动编号字段引用了组件。我尝试了许多不同类型的方法来执行此操作,您可以在我注释掉的代码中看到一些。到目前为止,我认为最接近正确代码的是什么,现在的错误是 Access 要求我提供 rPID 的参数值,即使它在 Dlookup 函数中找到了值。我假设rAID 部分也是如此。
否则,当您使用 INSERT 然后 UPDATE 方法时,我会收到 Key Violations 错误,您看到的注释已被注释掉。
表单名为HOTEntry
非常感谢任何关于我的问题的建议,我是一名学生,这是我第一次尝试在专业应用程序中使用我所学的知识,因此需要任何和所有建设性的批评!抱歉,如果这是一个相当具体的问题,但我真的可以在这方面使用帮助,因为我已经研究了两天但无济于事......
我的代码:
Sub HOTParts2()
Dim rPID As Integer
Dim rAID As Integer
Dim dbs As DAO.Database
Dim sqlstr1 As String
Dim sqlstr2 As String
Dim sqlstr3 As String
Dim sqlstr4 As String
Set dbs = CurrentDb
'sqlstr1 = "INSERT INTO Assembly ( PID, ModelNum, ModelRev, ModelDescription ) " _
' & "SELECT (PID,Forms!HOTEntry!txtHotModel, Forms!HOTEntry!txtHotRev, Forms!HOTEntry!txtHotDes)" _
' & "FROM Part " _
' & "WHERE Part.PartName = Forms!HOTEntry!txtPartName AND Part.Config = Forms!HOTEntry!txtConfigEntry AND Part.Rev = Forms!HOTEntry!txtRevEntry"
sqlstr1 = "INSERT INTO Assembly ( ModelNum, ModelRev, ModelDescription,PID ) " _
& "VALUES (Forms!HOTEntry!txtHotModel, Forms!HOTEntry!txtHotRev, Forms!HOTEntry!txtHotDes," & "rPID" & ");"
'
'sqlstr2 = "UPDATE Assembly " _
' & "SET PID =" & rPID & " " _
' & "WHERE Assembly.ModelNum = Forms!HOTEntry!txtHotModel And Assembly.ModelDescription = Forms!HOTEntry!txtHotDes And Assembly.ModelRev = Forms!HOTEntry!txtHotRev;"
'
'sqlstr3 = "INSERT INTO MachineOrder ( AID, Serial, CustName ) " _
' & "SELECT (AID,Forms!HOTEntry!txtHotSerial, Forms!HOTEntry!txtHotCust)" _
' & "FROM Assembly" _
' & "WHERE Assembly.Model=Forms!HOTEntry!txtHotModel And ModelDescription= Forms!HOTEntry!txtHotDes And ModelRev = Forms!HOTEntry!txtHotRev; "
sqlstr3 = "INSERT INTO MachineOrder (Serial, CustName, AID ) " _
& "VALUES (Forms!HOTEntry!txtHotSerial, Forms!HOTEntry!txtHotCust," & "rAID" & ");"
'
'sqlstr4 = "UPDATE MachineOrder " _
' & "SET AID =" & rAID & " " _
' & "WHERE AID IS NULL;"
rPID = DLookup("PID", "Part", "PartName = " & "'" & Forms!HOTEntry!txtPartName & "'" & " And " & "Config = " & "'" & Forms!HOTEntry!txtConfigEntry & "'" & " And " & "Rev = " & "'" & Forms!HOTEntry!txtRevEntry & "'")
DoCmd.RunSQL sqlstr1
'DoCmd.RunSQL sqlstr2
rAID = DLookup("AID", "Assembly", "ModelNum = " & "'" & Forms!HOTEntry!txtHotModel & "'" & " And " & "ModelDescription = " & "'" & Forms!HOTEntry!txtHotDes & "'" & " And " & "ModelRev = " & "'" & Forms!HOTEntry!txtHotRev & "'")
DoCmd.RunSQL sqlstr3
'DoCmd.RunSQL sqlstr4
End Sub
【问题讨论】:
标签: ms-access vba foreign-keys insert-into