如何从一个表复制记录集并添加到另一个表?

时间:2013-04-03 09:04:11

标签: vba ms-access access-vba recordset

我有两个表格,我有一个表格链接到其中一个表格。我想检查一个值,如果是,则使用VBA将记录添加到另一个表中。 有人可以帮帮我吗?

这是我的代码,但它不起作用:

Dim rec1 As DAO.Recordset
Dim rec2 As DAO.Recordset

Set rec1 = CurrentDb.OpenRecordset("TotalTPAq")
Set rec2 = CurrentDb.OpenRecordset("Visi")

rec1.MoveFirst
Do Until rec1.EOF

    If rec1!Date = PlanDate.Value Then ' planDate is a text box
        rec2.AddNew
        rec2![Planing Date History] = PlanDate.Value
        rec2.Update
        rec2.Close
    End If
    rec1.MoveNext
Loop
rec1.Close

Set rec2 = Nothing
Set rec1 = Nothing

DoCmd.Close

1 个答案:

答案 0 :(得分:3)

这应该为您提供一个开始:

'Run query to fill table
Private Sub btnRnQry_Click()

    'No value entered
    If IsNull(Me.txtEntry) Or Me.txtEntry = "" Then
        MsgBox ("Is null or empty")
    Else
        'Assign value to variable
        Dim entry As String
        entry = Me.txtEntry

        Dim sql As String
        sql = "INSERT INTO tableTwo ([First Name],Surname,[Phone Number] )" & _
              "SELECT * " & _
              "FROM tableOne " & _
              "WHERE [First Name] = '" & entry & "';"

        'Run the SQL
        DoCmd.RunSQL sql

    End If

End Sub