QueryDef Object, QueryDefs Collection Example (MDB)

The following example checks to see if there is a query called RecentHires in the current database, and deletes it from the QueryDefs collection if it exists. Then the procedure creates a new QueryDef object and opens it in Datasheet view.

Sub NewQuery()
    Dim dbs As Database, qdf As QueryDef
    Dim strSQL As String

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Refresh QueryDefs collection.
    dbs.QueryDefs.Refresh
    ' If RecentHires query exists, delete it.
    For Each qdf in dbs.QueryDefs
        If qdf.Name = "RecentHires" Then
            dbs.QueryDefs.Delete qdf.Name
        End If
    Next qdf
    ' Create SQL string to select employees hired on or
    ' after 1-1-94.
    strSQL = "SELECT * FROM Employees WHERE HireDate >= #1-1-94#;"
    ' Create new QueryDef object.
    Set qdf = dbs.CreateQueryDef("RecentHires", strSQL)
    ' Open query in Datasheet view.
    DoCmd.OpenQuery qdf.Name
    Set dbs = Nothing
End Sub