如何从一个表读取记录并写入具有相应记录的另一个表?

时间:2016-09-28 17:28:28

标签: sql vba ms-access access-vba

我试图从一个访问表中读取发送电子邮件," Email1"然后写入相应的记录" Email2"与日期。要查找相应的记录,两个表中的RecID字段将匹配。我一直在返回错误"语法错误"突出显示以下这一行" rs1.Edit其中rs!MaxOfForm_Record_Number = rs1.MaxOfForm_Record_Number"

   Function EmailTest1()

    Dim rs As Recordset
    Dim strBody As String
    Dim strBody2 As String
    Dim strRecipient As String
    Dim rs1 As Recordset
    Set rs1 = CurrentDb.OpenRecordset("Email2")
    Set rs = CurrentDb.OpenRecordset("Email1")
    Dim strName As String
    Dim strProject As String
    Dim strLastDate As String
    Dim strNow As String
    Dim emailcheck As String

    rs.MoveLast
    rs.MoveFirst

    For i = 1 To rs.RecordCount

        If IsNull(rs!EmailStat) = True Then
         strNow = Now()
         strName = rs!Inspected_By
         strProject = rs!Site_Location
         strLastDate = rs!LastOfDate_Time_of_Inspection
         strBody2 = "BLah blah text "

         rs1.Edit where rs!RecID = rs1.RecID
         rs1![EmailStat].Value = strNow
         rs1.Update

         strBody = "blahblah"
         strRecipient = rs!Email
         DoCmd.SendObject , , , strRecipient, , , "Subject", strBody, False, False


         End If
         rs.MoveNext
    Next i

    Set rs = Nothing

    End Function

2 个答案:

答案 0 :(得分:2)

我不会为完整的OpenRecordset交易而烦恼,我只会做:

DoCmd.RunSQL "UPDATE Email2 SET EmailStat=#" & strNow & "# WHERE RecID=" & rs!RecID

附加说明: RecordCount并不完全值得信赖。我喜欢像这样循环:

rs.MoveFirst
Do while Not rs.EOF
    {Do Stuff}
    rs. MoveNext
  Loop

(这根本不检查没有记录,检查所有用途都没有记录: rs.EOF=True AND rs.BOF=true 在rs.MoveFirst之前,否则你会得到一个错误)

答案 1 :(得分:1)

你需要找到记录 - 然后编辑它 你不能像在尝试那样在一条线上做到这一点

替换:

rs1.Edit where rs!RecID = rs1.RecID

使用:

rs1.FindFirst "RecID = " & rs!RecID
rs1.Edit
  

编辑 - 添加对NoMatch的检查

注意 - 您还应该在FindFirst尝试后检查rs1.NoMatch,
除非你确定每条记录都有一个RecID匹配