全部,
我现在正为一个问题苦苦挣扎。我在互联网上到处都是,但没有找到解决方案。我有两个表,一个主表(tbl_D_opp_prod_offer)和一个明细表(tbl_D_opp_prod_offer_line)。用户可以在用户表单中选择在主表单中创建记录的副本,以开始更改新记录。详细表的相关记录也应重复。这是因为有时用户已经抓取另一行作为模板的速度更快。我简化了下面的示例。
主表包含:Opp_ID = PK(自动编号)项目(以及其他几个领域)
详细信息表包括:Opp_line_ID = PK(自动编号)Opp_ID = FK(数字)产品(以及其他几个领域)
我使用了两种方法,一种使用sql,一种使用记录集。两者都不起作用。当我debug.print sql路由作为新查询时,它可以工作。所以我不知道哪里出了问题。该关系具有强制参照完整性,级联更新和级联删除。我真的希望有人能帮上忙,我正在脱发;-)因为我已经将其存储在主窗体的Form类对象中,所以这可能是个问题吗?还是违反密钥?我该如何更改?
我为SQL解决方案提供的代码:
Public Function duplicate()
'Find selected record
DoCmd.SearchForRecord , , , "[Project_ID] = " & "'" & [Forms]![Frm_Opp_prod_offer]! [lst_Edit_project_ID] & "'"
Dim OldId As Integer, NewId As Integer
' Read old ID
OldId = Me.Opp_ID
' copy main table records to new record
DoCmd.RunCommand acCmdSelectRecord
DoCmd.RunCommand acCmdCopy
DoCmd.RunCommand acCmdRecordsGoToNew
DoCmd.RunCommand acCmdSelectRecord
DoCmd.RunCommand acCmdPaste
' Read new ID
NewId = Me.Opp_ID
' Copy all records from old ID to new ID
S = "INSERT INTO [tbl_D_opp_prod_offer_line] (Opp_ID, Product) " & _
"SELECT " & NewId & " As Opp_ID, Product " & _
"FROM [tbl_D_opp_prod_offer_line] WHERE Opp_ID = " & OldId
Debug.Print S
Stop
' Hit Ctrl+G, copy SQL from Immediate Window to a new query
CurrentDb.Execute S, dbFailOnError
' Load copied records
Me!Frm_Opp_prod_offer_line.Form.Requery
End Function
`
通过Recordset解决方案:
Sub method2()
Dim rstSource As DAO.Recordset
Dim rstInsert As DAO.Recordset
Dim fld As DAO.Field
Dim strSQL As String
Dim lngLoop As Long
Dim lngCount As Long
Dim OldId As Integer, NewId As Integer
'Beginning is same
'Find selected record
DoCmd.SearchForRecord , , , "[Project_ID] = " & "'" & [Forms]![Frm_Opp_prod_offer]![lst_Edit_project_ID] & "'"
' Read old ID
OldId = Me.Opp_ID
' copy main table records to new record
DoCmd.RunCommand acCmdSelectRecord
DoCmd.RunCommand acCmdCopy
DoCmd.RunCommand acCmdRecordsGoToNew
DoCmd.RunCommand acCmdSelectRecord
DoCmd.RunCommand acCmdPaste
' Read new ID
NewId = Me.Opp_ID
strSQL = "SELECT * FROM tbl_D_opp_prod_offer_line WHERE Opp_ID = " & OldId
' Change this to the RecordsetClone of the subform.
Set rstInsert = CurrentDb.OpenRecordset(strSQL)
Set rstSource = rstInsert.Clone
With rstSource
lngCount = .RecordCount
For lngLoop = 1 To lngCount
With rstInsert
.AddNew
For Each fld In rstSource.Fields
With fld
If .Attributes And dbAutoIncrField Then
' Skip Autonumber or GUID field.
If .Name = "Opp_ID" Then ' Name of FK.
rstInsert.Fields(.Name).Value = NewId ' The new ID of the parent.
Else
' Copy field content.
rstInsert.Fields(.Name).Value = .Value
End If
End If
End With
Next
.Update
End With
.MoveNext
Next
rstInsert.Close
.Close
End With
Set rstInsert = Nothing
Set rstSource = Nothing
End Sub
一旦在表单上创建了新的主记录,在创建从属记录之前,必须首先提交到表。
一种强制提交记录的方法:
If Me.Dirty Then Me.Dirty = False