running an SQL query

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?
 
V

Van T. Dinh

RunSQL can only be used with the *Action* SQL, i.e. Append / Update /
Delete... and not a Select SQL.
 
G

google

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!
 
G

Guest

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

Access Form Coding 7
Run-time error '2342' 5
A SQL statement in VBA 7
SQL Query 4
unvalid sql 2
DoCmd.RunSQL 9
Select SQL in VBA - Possible 4
VBA -- SQL 9

Top