9

How can I execute a query to return records in an ms-access database using VBA code?

2
  • yes it will return paths to pictures stored locally in db and id of each Commented Dec 31, 2010 at 3:46
  • Where do you want them returned and how? Commented Jun 12, 2011 at 21:22

2 Answers 2

18

How about something like this...

Dim rs As RecordSet
Set rs = Currentdb.OpenRecordSet("SELECT PictureLocation, ID FROM MyAccessTable;")

Do While Not rs.EOF
   Debug.Print rs("PictureLocation") & " - " & rs("ID")
   rs.MoveNext
Loop
Sign up to request clarification or add additional context in comments.

Comments

14

Take a look at this tutorial for how to use SQL inside VBA:

http://www.ehow.com/how_7148832_access-vba-query-results.html

For a query that won't return results, use (reference here):

DoCmd.RunSQL

For one that will, use (reference here):

Dim dBase As Database
dBase.OpenRecordset

4 Comments

@Remou please more info on DoCmd.RunQuery, i don't want to use SQL, I have the Query already done in ms-access
oops Openquery : msdn.microsoft.com/en-us/library/bb238028(v=office.12).aspx . With Open query you will get warning messages, but they can be turned off and on again if they become a problem.
@Remou thanks, i have a table in ms-access that contains paths to pictures locally and want to print that, pls help me chek this link stackoverflow.com/questions/4567204/…
It's simply never a good idea to turn off SetWarnings. For one, you will then not know if something went wrong. That is, DoCmd.SetWarnings False doesn't just turn off the confirmation prompt, but also turns off the reporting of any errors. And in the case of DoCmd.RunSQL, you can't know that your entire update succeeded, because the SQL will be executed and as many UPDATEs/INSERTs as possible completed. I do not know if DoCmd.OpenQuery has the same deficiency, but it likely does. For a replacement that implements @Remou's first suggestion, search SO for my SQLRun() function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.