423,846 Members | 2,048 Online
Bytes IT Community
Submit an Article
Got Smarts?
Share your bits of IT knowledge by writing an article on Bytes.

Access VBA DAO recordset loop using two recordsets

MMcCarthy
Expert Mod 10K+
P: 14,534
The following code is simply an example of some code that processes through two recordsets. It can be helpful for anyone curious as to how to start processing with recordsets (Which objects to refer to & how to set them up correctly etc), as well as for those who want a quick run-through of some basic multi-recordset logic.
Expand|Select|Wrap|Line Numbers
  1. Function yourFunctionName() 
  2. Dim db As DAO.Database
  3. Dim rs1 As DAO.Recordset
  4. Dim rs2 As DAO.Recordset
  5.  
  6.   Set db = CurrentDb() 
  7.   Set rs1 = db.OpenRecordset("Query1") 
  8.   Set rs2 = db.OpenRecordset("Query2")
  9.  
  10.   If rs1.RecordCount=0 Then Exit Sub
  11.  
  12.   rs1.MoveFirst 
  13.   ' loop through each record in the first recordset
  14.   Do Until rs1.EOF
  15.     ' If matching record is found then update field in 
  16.     ' second recordset to value you determine
  17.    If rs2.RecordCount=0 Then Exit Sub
  18.     rs2.MoveFirst
  19.     Do Until rs2.EOF
  20.       If rs1![FieldName] = rs2!FieldName Then
  21.         rs2.Edit
  22.         rs2![FieldName] = 'Your Value'
  23.         rs2.Update
  24.       End If
  25.       rs2.MoveNext
  26.     Loop
  27.     rs1.MoveNext
  28.   Loop
  29.  
  30.   rs1.Close 
  31.   rs2.Close 
  32.   Set rs1 = Nothing
  33.   Set rs2 = Nothing
  34.   Set db = Nothing
  35.  
  36. End Function
Remember this is just an example and not by any means the only way of achieving this.
Jan 1 '07 #1
Share this Article
Share on Google+
4 Comments


P: 1
This was a clear, concise example for a novice like me. Thanks for the effort. I sure wish I had seen this on Friday.
Bill
Feb 24 '08 #2

P: 15
This was really helpful, so thank you for posting.

Brian
Feb 26 '08 #3

ahmedtharwat19
P: 55
perfect code

i use it in my project

thank you

ahmed tharwat
Jun 6 '10 #4

P: n/a
Avi Pawar
This the best example source code for me. I am going to use it in my project. I am sure, after making some changes I will get the result I want. Thanks a lot
Oct 1 '10 #5