[Access, VBA] prüfen, ob ein Objekt bereits existiert
Gepostet am: Jun 16, 2013 1:24:58 PM
Da man für Tabellen udgl nicht mit den selben Namen anlegen sollte, wie bereits bestehende Objekte, sollte man zuvor überprüfen, ob das Element mit dem Namen bereits existiert.
ObjectExists
' Pass the Object type: Table, Query, Form, Report, Macro, Module, All' Pass the Object NameFunction 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" Or strObjectType = "All" Then For Each tbl In db.TableDefs If tbl.Name = strObjectName Then ObjectExists = True Exit Function End If Next tbl ElseIf strObjectType = "Query" Or strObjectType = "All" 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" Or strObjectType = "All" 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" Or strObjectType = "All" 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 passed, must be Table, Query, Form, Report, Macro, Module, or All" End If End Function
Um beispielsweise zu prüfen, ob eine Tabelle mit dem Namen "Haupttabelle" existiert
> msgbox ObjectExists("Table","Haupttabelle")