Private Sub cmdCopyOrder_Click()
On Error GoTo Err_Handler
'Purpose: Duplicate the main form record and related records in the subform.
Dim str2Sql As String
Dim strSQL As String
Dim NewOrderID As Long 'Primary key value of the new record.
Dim OldOrderID As Long 'Primary key value of the old record.
Dim NewOrderDetailID As Long
Dim db As DAO.Database
Dim qd As DAO.QueryDef
Dim FromQD As DAO.QueryDef
Dim FromRS As DAO.Recordset
Dim ToTD As DAO.TableDef
Dim ToRS As DAO.Recordset
'Save any edits first
If Me.Dirty Then
Me.Dirty = False
End If
'Make sure there is a record to duplicate.
If Me.NewRecord Then
MsgBox "Select the record to duplicate."
Exit Sub
End If
'Duplicate the main record: add to form's recordset clone.
OldOrderID = Me.OrderID
With Me.RecordsetClone
.AddNew
!CustID = Me.cboCustID
!JobName = Me.JobName
!Notes = Me.Notes
!TermsID = Me.TermsID
!ShippingID = Me.ShippingID
!CustConID = Me.cboCustConID
!CustLocID = Me.cboCustLocID
!OrderNumber = Nz(DMax("OrderNumber", "tblOrders"), 0) + 1
!OrderDate = Date
'' !Expires = Date + 30
.Update
'Save the primary key value, to use as the foreign key for the related records.
.Bookmark = .LastModified
NewOrderID = !OrderID
'Display the new duplicate.
Me.Bookmark = .LastModified ' move form to position on the newly created record.
End With
'Duplicate the related Item records using DAO recordset. Append Accessories with append query inside loop
Set db = CurrentDb()
Set ToTD = db!tblOrderDetails
Set ToRS = ToTD.OpenRecordset
Set FromQD = db.QueryDefs!qOrderCopyDetails
FromQD.Parameters!EnterOldOrderID = OldOrderID
Set FromRS = FromQD.OpenRecordset(dbOpenDynaset, dbSeeChanges)
With FromRS
.MoveFirst
Do Until .EOF = True
ToRS.AddNew
ToRS!ItemNo = !ItemNo
ToRS!EstID = !EstID
ToRS!ModelNo = !ModelNo
ToRS!Description = !Description
ToRS!Qty = !Qty
ToRS!Price = !Price
ToRS!AccessPrice = !AccessPrice
ToRS!OrderID = NewOrderID
NewOrderDetailID = ToRS!OrderDetailID
ToRS.Update
'' copy accessories
Set qd = db.QueryDefs!qCopyAppendOrderAcc
qd.Parameters!EnterOldOrderDetailID = !OrderDetailID
qd.Parameters!EnterNewOrderDetailID = NewOrderDetailID
qd.Execute dbFailOnError
.MoveNext
Loop
End With
Me.SfrmOrderDetails.Requery
ToRS.Close
FromRS.Close
Set ToRS = Nothing
Set FromRS = Nothing
Set db = Nothing
Exit_Handler:
Exit Sub
Err_Handler:
Select Case Err.Number
Case 3021, 2501 ' update cancelled
Resume Exit_Handler
Case Else
MsgBox Err.Number & "--" & Err.Description
Resume Exit_Handler
End Select
End Sub