The Usual Approach
The idea for this function came to me while responding to a question in the forums on how to check if a query exist. The usual approach is to assign the query's name to a QueryDef object and trap the error, if the query does not exist. For example:
Public Function QueryExists(QueryName As String) As Boolean 'thedbguy@gmail.com '11/5/2021
Dim qdf As DAO.QueryDef
On Error Resume Next
Set qdf = CurrentDb.QueryDefs(QueryName)
If Err = 0 Then QueryExists = True Else QueryExists = False End If
Set qdf = Nothing
End Function
A Better Approach
Public Function QueryExists_1(QueryName As String) As Boolean'thedbguy@gmail.com'11/5/2021Dim qdf As DAO.QueryDefDim blnReturn As BooleanFor Each qdf In CurrentDb.QueryDefsIf qdf.Name = QueryName ThenblnReturn = TrueExit ForEnd IfNextQueryExists_1 = blnReturnEnd Function
An Even Better Approach
Option Compare DatabaseOption ExplicitPublic Enum dbgObjectTypedbgTable = 1dbgQuery = 5dbgForm = -32768dbgReport = -32764dbgMacro = -32766dbgModule = -32761dbgODBCLinkedTable = 4dbgOtherLinkedTable = 6End EnumPublic Function ObjectExists(ObjectName As String, ObjectType As dbgObjectType, _ Optional DatabasePath As String) As Boolean'thedbguy@gmail.com'11/5/2021Dim blnReturn As BooleanIf DatabasePath = "" ThenblnReturn = DCount("*", "MSysObjects", "[Name]='" _ & ObjectName & "' AND [Type]=" & ObjectType)ElseIf Dir(DatabasePath) = "" Then'MsgBox "Cannot find " & DatabasePath, vbInformation, "Info!"Debug.Print "Cannot find " & DatabasePathblnReturn = FalseElseblnReturn = CurrentDb.OpenRecordset("SELECT Count(*) FROM [;Database=" _& DatabasePath & "].MSysObjects WHERE [Name]='" _& ObjectName & "' AND [Type]=" & ObjectType)(0)End IfObjectExists = blnReturnEnd Function
Extension
Public Function TableExists(TableName As String, Optional DatabasePath As String) As BooleanTableExists = ObjectExists(TableName, dbgTable, DatabasePath)End FunctionPublic Function FormExists(FormName As String, Optional DatabasePath As String) As BooleanFormExists = ObjectExists(FormName, dbgForm, DatabasePath)End Function