|
看下面代码。这个不仅复制了主窗体的记录,同时也可以复制子窗体的记录(如有有的话)。这个方法是我目前为止看到的最优雅的复制上一个记录的方法。详细说明还可以看作者原文(链接如下)。
http://allenbrowne.com/ser-57.html
Private Sub cmdDupe_Click()
'On Error GoTo Err_Handler
'Purpose: Duplicate the main form record and related records in the subform.
Dim strSql As String 'SQL statement.
Dim lngID As Long 'Primary key value of the new record.
'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."
Else
'Duplicate the main record: add to form's clone.
With Me.RecordsetClone
.AddNew
!CustomerID = Me.CustomerID
!EmployeeID = Me.EmployeeID
!OrderDate = Date
'etc for other fields.
.Update
'Save the primary key value, to use as the foreign key for the related records.
.Bookmark = .LastModified
lngID = !OrderID
'Duplicate the related records: append query.
If Me.[Orders Subform].Form.RecordsetClone.RecordCount > 0 Then
strSql = "INSERT INTO [Order Details] ( OrderID, ProductID, Quantity, UnitPrice, Discount ) " & _
"SELECT " & lngID & " As NewID, ProductID, Quantity, UnitPrice, Discount " & _
"FROM [Order Details] WHERE OrderID = " & Me.OrderID & ";"
DBEngine(0)(0).Execute strSql, dbFailOnError
Else
MsgBox "Main record duplicated, but there were no related records."
End If
'Display the new duplicate.
Me.Bookmark = .LastModified
End With
End If
Exit_Handler:
Exit Sub
Err_Handler:
MsgBox "Error " & Err.Number & " - " & Err.Description, , "cmdDupe_Click"
Resume Exit_Handler
End Sub |
|