MS Access VBA – Determine if a Query Exists

The following procedure checks to see if a query exists in the current database.

'---------------------------------------------------------------------------------------
' Procedure : DoesQryExist
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Determine if the specified query exists or not in the current database
' Copyright : The following may be altered and reused as you wish so long as the
'             copyright notice is left unchanged (including Author, Website and
'             Copyright).  It may not be sold/resold or reposted on other sites (links
'             back to this site are allowed).
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sQueryName: Name of the query to check the existence of
'
' Usage Example:
' ~~~~~~~~~~~~~~~~
' DoesQryExist("Query1")
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2010-Feb-02             Initial Release
'---------------------------------------------------------------------------------------
Function DoesQryExist(sQueryName As String) As Boolean
   Dim db   As DAO.Database
   Dim qdf  As QueryDef
  
On Error GoTo Error_Handler
   'Initialize our variable
   DoesQryExist = False 'Not strictly necessary as it is the default value
  
   Set db = CurrentDb()
   Set qdf = db.QueryDefs(sQueryName)
  
   DoesQryExist = True  'If we made it to here without triggering an error
                        'the query exists

Error_Handler_Exit:
   On Error Resume Next
   Set qdf = Nothing
   Set db = Nothing
   Exit Function

Error_Handler:
   If Err.Number = 3265 Then
      'If we are here it is because the query could not be found
   Else
      MsgBox "MS Access has generated the following error" & vbCrLf & vbCrLf & "Error Number: " & _
      Err.Number & vbCrLf & "Error Source: DoesQryExist" & vbCrLf & "Error Description: " & _
      Err.Description, vbCritical, "An Error has Occurred!"
   End If
   Resume Error_Handler_Exit
End Function

Another alternate method to using this function would be to loop through all the QueryDefs to see if the specified name matched any query in the list, but I believe this above listed function is better.

2 responses on “MS Access VBA – Determine if a Query Exists

  1. Toni Muller

    And 10 years later, this code is still awesome! Much faster than looping through the QueryDefs collection. Thank you!