Link to home
Start Free TrialLog in
Avatar of Svgmassive
Svgmassive

asked on

Loop through recordets and update fields

I have imported a excel file into ms access table i am looking for the fastest way to loop through the records to update certain fields.
I am looking for a procedure that uses an array and one that doesn't. If that possible.
Thanks
Avatar of John Tsioumpris
John Tsioumpris
Flag of Greece image

Dim rst as DAO.Recordset
Set rst=CurrentDb.OpenRecordSet(NameOf_YourTable)
With rst
While Not .EOF
.Edit
.Fields(Name of the field you want to edit)=Some Value
.Update
Wend
End With
Rst.Close

Just put the whole code in an array iteration to have all the tables that need editing and you should be good to good
ASKER CERTIFIED SOLUTION
Avatar of Dale Fye
Dale Fye
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks Dale... typing code on the mobile is not my best
To add a bit more...
Assume you have 2 tables to update e.g. Table1,Table2
Dim tablesForUpdate(1) as String
Dim rst as DAO.Recordset
tablesForUpdate(0) = "Table1"
tablesForUpdate(1) = "Table2"
For i = Lbound(tablesForUpdate) to Ubound(tablesForUpdate)


Set rst=CurrentDb.OpenRecordSet(tablesForUpdate(i))
With rst
While Not .EOF
.Edit
.Fields(Name of the field you want to edit)=Some Value
.Update
.MoveNext
Wend
End With
Rst.Close
Next

Open in new window

Similar you could have an array for the fields to Update and "insert" it in the part where the Editing takes place.
The fastest updating method for your tables would be to invoke queries, not to loop through recordsets.
Example:
dbEngine(0)(0).Execute "Update Table1 Set fieldname = value, fieldname2 = value2"

Open in new window

You would add a Where clause to the SQL to limit the rows affected by the query.
It sounds like the author is an Excel user and not an experienced Access user, thus the dependence on looping vs SQL.
Once Excel users see what you can do with SQL, The world becomes a new place for them and they start using Excel just for data import and report data export, and do all their processing in Access/SQL.

You can also update tables in Excel with SQL and do away with all the offsets, dictionary objects and classes - that the old, clunky, hard way of doing things - and totally unnecessary!