单击从一个表中删除记录并将其更新为另一个表的事件

时间:2018-03-15 23:02:46

标签: sql vba ms-access access-vba

我目前有一个允许用户填写字段的表单。

表单的工作方式:

当表单完成并单击事件类型按钮时,将从其链接表中删除该记录。删除录制后,我希望将删除的记录移动到另一个表。换句话说,将记录从一个表移动到另一个表,将其从原始表中删除。

使用简单的SQL语句可以实现吗?是否有任何消极方面试图实现这一目标?

Private Sub cmdDelete_Click()
    On Error Resume Next
    RunCommand acCmdDeleteRecord
End Sub

上面的代码可以完美地删除记录,它知道从右表中删除它,因为我使用了表单向导来创建它。我想我可能需要添加一个insert语句来将记录移动到另一个表中。

更新后的代码会抛出一个complie错误:语法错误。这是由于换行吗?

Private Sub Command22_Click()

'If Len(CorrectionMadeByContracting & vbNullString) = 0 Then _
   ' MsgBox "Field cannot be left blank"

   ' On Error Resume Next
   ' RunCommand acCmdDeleteRecord

    Dim rsSource As DAO.Recordset
    Dim rsDestination As DAO.Recordset
    Set rsDestination = CurrentDb.OpenRecordset("Inquiries")
    Set rsSource = Me.Recordset 'Current form record
    Dim fld As DAO.Field
    If Not rsSource.EOF And Not rsSource.BOF
        rsDestination.AddNew 'Add a record to the destination
        For Each fld In rsSource.Fields 'Copy all the fields
            If (fld.Attributes And dbAutoIncrField) <> dbAutoIncrField Then 'Don't copy auto increment
                rsDestination.Fields(fld.Name).Value = fld.Value
            End If
        Next
        rsDestination.Update
        rsSource.Delete 'Delete the record from the source
    End If

1 个答案:

答案 0 :(得分:1)

虽然使用标志肯定有效,但您可以使用记录集轻松移动记录

(此代码假定源表和目标表之间的字段名称和字段类型相同。)

Private Sub cmdDelete_Click()
    Dim rsSource As DAO.Recordset
    Dim rsDestination As DAO.Recordset
    Set rsDestination = CurrentDb.OpenRecordset("MyDestination")
    Set rsSource = Me.Recordset 'Current form record
    rsSource.Bookmark = Me.Bookmark 'Move recordset to current record
    Dim fld As DAO.Field
    If Not rsSource.EOF And Not rsSource.BOF Then
        rsDestination.AddNew 'Add a record to the destination
        For Each fld in rsSource.Fields 'Copy all the fields
            If (fld.Attributes And dbAutoIncrField) <> dbAutoIncrField Then 'Don't copy auto increment
                rsDestination.Fields(fld.Name).Value = fld.Value
            End If
        Next
        rsDestination.Update    
        rsSource.Delete 'Delete the record from the source
    End If
    Me.Requery 'Enforce requery to get accurate record count
End Sub