Access - Primärschlüssel!

Frage: Wie erstelle ich eine Access-Datenbank mit einer Tabelle und einem Primärschlüssel - am besten noch per "Late Binding" um die eventuell auftretenden Verweisprobleme zu umgehen? So:

Access - Primärschlüssel...[ZIP, 40 KB]

Code:
Option Explicit
' Pfad- und Dateiname anpassen!
Const strFileName As String = "C:\Temp\Test1.mdb"
Public Sub CreateDataBase()
Dim catCatalog As Object
Dim objTable As Object
Dim objIndex As Object
Dim objConn As Object
On Error GoTo Fin
Set objConn = CreateObject("ADODB.Connection")
Set catCatalog = CreateObject("ADOX.Catalog")
catCatalog.Create "Provider=Microsoft.Jet.OLEDB.4.0; " & _
"Data Source=" & strFileName
With objConn
.CursorLocation = 3 ' = adUseClient
.Provider = "Microsoft.Jet.OLEDB.4.0"
.Properties("Data Source") = strFileName
.Open
End With
Set objIndex = CreateObject("ADOX.Index")
Set objTable = CreateObject("ADOX.Table")
With objTable
.Name = "Lieferanten"
.ParentCatalog = catCatalog
.Columns.Append "Primaer", 3 ' = adInteger
With .Columns("Primaer")
.Properties("Description") = "Schluessel"
.Properties("Autoincrement") = True
End With
.Columns.Append "Name", 202, 60 ' 202 = adVarWChar
With .Columns("Name")
.Properties("Description") = "Nachname"
.Properties("Jet OLEDB:Allow Zero Length") = True
.Properties("Nullable") = True
End With
End With
catCatalog.Tables.Append objTable
With objIndex
.Name = "PrimaryKey"
.Columns.Append "Primaer"
.PrimaryKey = True
.Unique = True
End With
objTable.Indexes.Append objIndex
Fin:
If Err.Number <> 0 Then MsgBox "Fehler: " & _
Err.Number & " (" & Err.Description & ")"
If Not objConn Is Nothing And objConn.State = 1 Then objConn.Close
Set objIndex = Nothing
Set objTable = Nothing
Set catCatalog = Nothing
Set objConn = Nothing
End Sub

Kommentare

Beliebte Posts aus diesem Blog

Formeln - auch Array - per VBA eintragen...

Alle Dateien eines Ordners - Optional mit Unterordner

Excel -> Word in Textmarken (Bookmarks)...