从表单和子表单复制数据

时间:2018-02-12 10:37:00

标签: vba ms-access access-vba

我的Form每次只显示一条记录。从2个表([Data Processing List][Attributes])中读取数据。在Form中,有一个Subform从第三个表([Security Measures])获取数据,并且只显示与Form中所选记录相关的行。

enter image description here

Form我有按钮Copy,其目的是复制所选记录。

问题是它只复制表单的2个表的数据而不复制Subform的表。

我做错了吗?

Copy按钮的代码如下(简化):

Private Sub Copy()

            DoCmd.RunCommand acCmdSelectRecord
            DoCmd.RunCommand acCmdCopy
            DoCmd.RunCommand acCmdRecordsGoToNew
            DoCmd.RunCommand acCmdSelectRecord
            DoCmd.RunCommand acCmdPaste

End Sub

2 个答案:

答案 0 :(得分:0)

当需要复制子窗体记录时,这不会保持基本 - 复制/粘贴始终只影响活动窗体的当前/选择记录。

您需要先存储旧ID,然后复制主记录,读取新ID,然后使用这两个ID复制子表单记录。

像这样(航空代码):

Private Sub Copy()

    Dim OldId As Long, NewId As Long
    Dim S As String

    ' Read old ID
    OldId = Me!ID
    ' copy main records
    DoCmd.RunCommand acCmdSelectRecord
    DoCmd.RunCommand acCmdCopy
    DoCmd.RunCommand acCmdRecordsGoToNew
    DoCmd.RunCommand acCmdSelectRecord
    DoCmd.RunCommand acCmdPaste
    ' Read new ID
    DoCmd.RunCommand acCmdSaveRecord    ' not sure if needed
    NewId = Me!ID

    ' Copy all records from old ID to new ID
    ' TODO: add missing columns
    S = "INSERT INTO [Security Measures] (ID_SM, System, Note) " & _
        "SELECT " & NewId & " AS ID_SM, System, Note " & _
        "FROM [Security Measures] WHERE ID_SM = " & 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!mySubform.Form.Requery

End Sub

BTW,[Security Measures]本身应该有一个主键。

答案 1 :(得分:0)

或者您可以完全跳过所有DoCmd内容并直接在表单的记录集上操作:

  • 首先复制父记录
  • 然后复制子记录

Duplicate record and records in subform