Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code to loop through all records in MS Access

Tags:

vba

ms-access

I need a code to loop through all the records in a table so I can extract some data. In addition to this, is it also possible to loop through filtered records and, again, extract data? Thanks!

like image 237
Ali Avatar asked May 03 '11 01:05

Ali


People also ask

Do While loop in MS Access VBA?

A Do… While loop is used when we want to repeat a set of statements as long as the condition is true. The condition may be checked at the beginning of the loop or at the end of the loop.

What is DAO recordset in Access?

A dynaset-type Recordset object is a dynamic set of records that you can use to add, change, or delete records from an underlying database table or tables. A dynaset-type Recordset object can contain fields from one or more tables in a database.


1 Answers

You should be able to do this with a pretty standard DAO recordset loop. You can see some examples at the following links:
http://msdn.microsoft.com/en-us/library/bb243789%28v=office.12%29.aspx
http://www.granite.ab.ca/access/email/recordsetloop.htm

My own standard loop looks something like this:

Dim rs As DAO.Recordset Set rs = CurrentDb.OpenRecordset("SELECT * FROM Contacts")  'Check to see if the recordset actually contains rows If Not (rs.EOF And rs.BOF) Then     rs.MoveFirst 'Unnecessary in this case, but still a good habit     Do Until rs.EOF = True         'Perform an edit         rs.Edit         rs!VendorYN = True         rs("VendorYN") = True 'The other way to refer to a field         rs.Update          'Save contact name into a variable         sContactName = rs!FirstName & " " & rs!LastName          'Move to the next record. Don't ever forget to do this.         rs.MoveNext     Loop Else     MsgBox "There are no records in the recordset." End If  MsgBox "Finished looping through records."  rs.Close 'Close the recordset Set rs = Nothing 'Clean up 
like image 110
HK1 Avatar answered Sep 20 '22 00:09

HK1