访问VBA:使用`do while`循环更新记录集

时间:2017-11-13 03:52:06

标签: vba ms-access updates do-while

我想使用rs循环获得结果。 但是,我的结果只给出了一条记录......

我要做的是:

  1. 浏览rs(记录集)记录
  2. 检查rs2中的值是否等于username
  3. 如果是,请将rsrs2复制到Do While Not rs.BOF ' No of records in rs Do While Not rs2.EOF ' No of records in rs2 If Trim(rs2![pic_no]) = Trim(rs![pic]) Then rs![UserID] = rs2![NEW_USER] rs2.MoveNext rs.Update Else rs2.MoveNext rs.Update End If Loop rs.MovePrevious rs.Update Loop
  4. 转到下一条记录

    {{1}}

1 个答案:

答案 0 :(得分:1)

Do While Not rs.EOF                                  ' No of records in rs
    Do While Not rs2.EOF                             ' No of records in rs2
        If Trim(rs2![pic_no]) = Trim(rs![pic]) Then
            MsgBox rs!UserID
            rs.Edit
            rs.Fields("UserID") = rs2![NEW_USER]
            rs.Update
        End If
    rs2.MoveNext
    Loop
rs2.MoveFirst
rs.MoveNext
Loop

rs.Close
rs2.Close
Set rs = Nothing
Set rs2 = Nothing

End Sub

But why don't you simply use an update statement? Say you have two tables called TableUser (table you tefer to in rs) and TableNewUser (table you refer to in rs2). Your update statement would like like:

UPDATE TableUser, TableNewUser
SET TableUser.UserID = TableNewUser.NEW_USER
WHERE TableUser.pic = TableNewUser.pic_no;

Much easier. You can put this update statement in VBA code too (if there's a need/reason to do so).