Sometimes when developing automation with VBA in Access, it is important to return results from a SQL query string. For simplicity, all examples have been written as Functions. Please feel free to modify as needed.
Recordset Selection in VBA | Select One Record
There are many reasons why a developer would want to return only one result, for instance a count query. Here is an example for returning a single result:
Function getFirstRecord() Dim db AS DAO.Database, rs AS DAO.Recordset, strSQL as String Set db = Currentdb 'Define SQL Query strSQL = "SELECT COUNT(id) FROM table" Set rs = db.OpenRecordset(strSQL) 'Return Result getFirstRecord = rs.Fields(0) 'Close the Database db.Close set db = Nothing set rs = Nothing End Function
Recordset Selection in VBA | Return All Records
If you notice “rs.Fields(0)” in the result above, columns are returned based on “0” index. For example, if you were to run a SQL Query:
SELECT firstname, lastname, phone FROM table
Your result column index would look like:
- firstname = Fields(0)
- lastname = Fields(1)
- phone = Fields(2)
Here is an example for returning multiple results:
Function getAllRecords() Dim db AS DAO.Database, rs AS DAO.Recordset, strSQL as String Set db = Currentdb 'Define SQL Query strSQL = "SELECT firstname, lastname, phone FROM table" Set rs = db.OpenRecordset(strSQL) 'Return Result in Loop until end of results Do While NOT rs.EOF 'Insert code here to list elements 'We will loop through and popup a message box 'for this example MsgBox "Contact: " & rs.Fields(0) & " " & rs.Fields(1) & ": " & rs.Fields(2) 'This would pop a message box for each loop 'and display each contact called from the 'SQL query 'move to the next record for the next loop rs.MoveNext Loop 'Close the Database db.Close set db = Nothing set rs = Nothing End Function
VBA Run SQL Without Results
Most of the time it is not necessary to return results when running UPDATE, INSERT and DELETE queries. Here is how to run a SQL query in Access with VBA without returning results:
Function deleteRecord() 'disable warnings (optional) DoCmd.SetWarnings = False DoCmd.RunSQL "DELETE FROM table WHERE id=1" DoCmd.SetWarnings = True End Function
Please comment with questions, suggestions or improvements.
This is great for me as i’m a novice in vba, perfect!
May i ask if there’s any article like CRUD in vba?, Would be much appreciated, Thanks
Ryan McCormick says
I am happy that you like the article!
There are many ways to CRUD in Access depending on the project that you are working on. If you are just getting started with VBA and need to run actions with little setup, I suggest using DAO for reading and the DoCmd.RunSQL for INSERT, UPDATE, DELETE SQL actions.
If you are super novice with SQL as well, I recommend picking up a good primer book. Access has it’s own nuances of SQL, but most SQL functionality is universal across all relational database systems. If you are looking for a suggestion, I have reviewed and recommend this one: http://www.headfirstlabs.com/books/hfsql/
Jos Vermeulen says
You’re missing a rather important Not statement in your second example 😉
Ryan McCormick says
Crap! Thanks for the heads up! Updated.
Marcus Black says
I am trying to create a message box returning all of the values of a query which tells me which courses people need to re-sit.
I have a query called REPORT_INFO which returns the list of courses. There could be 1 or 20 or anywhere in between. The column name in the query is courses but I want the message box to read:
“Please be advised that the following courses have expired and must be re-taken:
[Course list here]” +signatures etc.
This has been something I have worked on for a few days now and I just haven’t been able to get my head around it! (Might be for a different thread but if you can point me in the right direction I’d be eternally grateful)
Ryan McCormick says
Sorry this is so late, everything has been super busy and my blog has not been updated in awhile. If this is still a problem, it sounds like you are attempting to run the message box results on the collection itself in the same function. You should extract this logic to it’s own function – within, define an empty string and loop through your recordset of results. Add the course from each row to the empty string with linebreak(or whatever your seperation delimiter is) and then return the string once your loop has completed.