To avoid errors you should always check before accessing an object if it exists. Sample call: MyTest = ObjectExists("Table", "MyTableName") or : If Not ObjectExists("Table", "MyTableName") Then ... '--------------------------------------------------------------------- ' ObjectExists: Find if the object exists in DB '--------------------------------------------------------------------- ' Pass the Object type: Table, Query, Form, Report, Macro, or Module ' Pass the Object Name ' Function returns boolean "Yes/NO" Function ObjectExists(strObjectType As String, strObjectName As String) As Boolean Dim db As Database Dim tbl As TableDef Dim qry As QueryDef Dim i As Integer Set db = CurrentDb() ObjectExists = False If strObjectType = "Table" Then For Each tbl In db.TableDefs If tbl.Name = strObjectName Then ObjectExists = True Exit Function End If Next tbl ElseIf strObjectType = "Query" Then For Each qry In db.QueryDefs If qry.Name = strObjectName Then ObjectExists = True Exit Function End If Next qry ElseIf strObjectType = "Form" Or strObjectType = "Report" Or strObjectType = "Module" Then For i = 0 To db.Containers(strObjectType & "s").Documents.Count - 1 If db.Containers(strObjectType & "s").Documents(i).Name = strObjectName Then ObjectExists = True Exit Function End If Next i ElseIf strObjectType = "Macro" Then For i = 0 To db.Containers("Scripts").Documents.Count - 1 If db.Containers("Scripts").Documents(i).Name = strObjectName Then ObjectExists = True Exit Function End If Next i Else MsgBox "Invalid Object Type, must be Table, Query, Form, Report, Macro, or Module" End If End Function '-------------- END ObjectExists ----------------------
Samples of VBA code I'm using in my daily tasks.
Friday, March 12, 2010
Does Access Object Exists
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment