2

I need to "physically" create an SQL query via VBA code. I know how to execute a query in VBA, but I need to save it in the menu. If I could I would post a picture. I'll try to make you imagine.

In the main screen of MS Access there's a bar on the left.

Just to make it clear, "Consulta" is Query in Portuguese.

If you didn't understand me, please excuse my lack of explanation. I'll be pleased to explain again.

1 Answer 1

11

I think you want:

If Not IsNull(DLookup("Type", "MSYSObjects", "Name='MyNewQuery'")) Then
    MsgBox "An object already exists with this name"
Else
    CurrentDb.CreateQueryDef "MyNewQuery", "SELECT * FROM Table1"
End If

EDIT re comments

Sub UpdateQuery(QueryName, SQL)
    ''Using a query name and sql string, if the query does not exist, ...
    If IsNull(DLookup("Name", "MsysObjects", "Name='" & QueryName & "'")) Then
        ''create it, ...
        CurrentDb.CreateQueryDef QueryName, SQL
    Else
        ''Other wise, update the sql.
        CurrentDb.QueryDefs(QueryName).SQL = SQL
    End If

End Sub

Note that deleting a query that does not exists will cause an error.

 DoCmd.DeleteObject acQuery, "NewQuery"
Sign up to request clarification or add additional context in comments.

9 Comments

It kinda worked. The statement validating the exintance of the object isn't running. It goes right through it and gives me an error that the object already exists. The problem is the crash that this error produces. If you can, give me another clue.
A crash suggest your database is corrupt, I am afraid. To ensure that this is the problem, you can check with a new database. After that, it would be worth looking at granite.ab.ca/access/corruptmdbs.htm
No, that's not what I meant. It's a crash in the code for not being able to handle the "Query already exists" error. The If Not IsNull line isn't working. But thank anyway... It really helped with my code.
@Patrick I am very surprised. I tested quite carefully before posting. What is the error? You realize you cannot create a query if a query or table already exists with that name (forms etc are a different story) ? If a query already exists with that name, Type will be 5 and you can update the sql with new sql, but not create a query.
Anyway, is there a way to destroy a query?
|

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.