running an SQL query

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

How do I run an SQL query through a command button?

I'm using this:

Private Sub Command1_Click()
DoCmd.RunSQL "SELECT Table1.F1 FROM Table1"
End Sub

But the following error appears:
A RunSQL action requires an argument consisting of an SQL statement.

What am I doing wrong?
 
RunSQL can only be used with the *Action* SQL, i.e. Append / Update /
Delete... and not a Select SQL.
 
Running a SELECT-query implies that you want results..... so, you need
some container to store the results. This can be done using the
Recordset-object:

'---------------------
'code start
'---------------------
dim db as database, rs as recordset
set db=currentdb()
set rs=db.openrecordset("MyQuery",dbOpenDynaSet)

while not rs.eof
debug.print rs![somefield].value

rs.movenext
wend

rs.close
db.close
'---------------------
'code end
'---------------------

This will open the query and cycle through all the records.


Good luck!
 
I see. Thanks!

For the benefit of others, what I did instead was just to save the SQL as a
query and then call this using the DoCmd.OpenQuery command.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Run-time error '2342' 5
A SQL statement in VBA 7
Access Form Coding 7
Insert variable into SQL string 2
SQL Query 4
sql query and WHERE condition 3
unvalid sql 2
Problem running an Action Query with VBA 4

Back
Top