tags:

views:

78

answers:

1

Suppose we have one table in Microsoft Access:

ID | Data

I need to select one row with a SQL query in VBA code.

In what variable to store that row? How to write that row back to the table in VBA? Could you please write simple code?

+2  A: 

You need to use a RecordSet object. This site provides many examples.

Here's a an example I put together from that site. This will grab all the records from tblName and update just the first record

UPDATE Answer changed to use DAO which is recommended when using Access Tables.

Dim rs As New DAO.Recordset

Set rs = CurrentDb.OpenRecordset("SELECT pkPeopleID, LastName FROM tblPeople", dbOpenDynaset)

rs.MoveFirst
rs.Edit
rs![Data] = "Foobar"
rs.Update

rs.Close
Set rs = Nothing

If you want a specific row rather than just the first row you can add a where clause e.g.

 Set rs = CurrentDb.OpenRecordset("SELECT pkPeopleID, LastName FROM tblPeople Where id = 123", dbOpenDynaset)

Or you could use FindFirst instead

rs.FindFirst "id = 123"
Conrad Frix
This will update that row or add else one?
Igor
@Conrad Frix. DAO is native to Access and should nearly always be used in preference to ADODB. @Igor, AddNew can be used to add a record to a recordset. You can also use a query : Set db=CurrentDB db.Execute "Insert into MyTable (MyText,Mydate,MyInt) Values ('ABC',#2010/11/25#,1) There are many ways to skin this particular cat :)
Remou
@igor I updated my answer based on your comment
Conrad Frix
@Remou. The link has both ADO and DAO syntax. I just grabbed one. Its been 10+ years since I've written VBA code professionally so I'm sure that you're right.
Conrad Frix
@Conrad: to make your answer useful, why not make it the more normal data access interface, DAO?
David-W-Fenton
@Remou @David I took your advice and updated the answer to use DAO
Conrad Frix
Good stuff. I took "where" out of FindFirst because I reckon you had a paste error.
Remou
There's no utility in `rs.MoveFirst` when the very next statement is `rs.FindFirst`. By default, the record pointer is on the first record, but if you're using .FindFirst, you don't really care where you're starting from (though .FindFirst starts from the first row of the recordset, which is one reason to optimize it when you can to use .FindNext and .FindPrevious; but that's a topic for another time...). Now, if I weren't doing a .FindFirst, I'd explicitly set the record pointer with .MoveFirst simply because I don't like depending on default behaviors.
David-W-Fenton
@Remou thanks. @David. I pulled the rs.MoveFirst.
Conrad Frix