Question : ADOX Add Column Multi-Step OLE DB errors

I am trying to add a column to an Access DB table using ADOX.  The column s/b an Autonumber-ReplicationID that autogenerates new values when records are added.

Here is my code:
    Dim tbl As ADOX.Table
    Dim col As New ADOX.Column
    Dim cat As New ADOX.Catalog
    Dim cnn As New ADODB.Connection
   
    Set cnn = New ADODB.Connection
    cnn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" _
                & "Data Source=" & sDBPath & ";"

    Set cat = New ADOX.Catalog
    Set cat.ActiveConnection = cnn
    Set tbl = cat.Tables(sTblName)
    Set col = New ADOX.Column
    With col
        .Name = sColName
        .Type = adGUID
        .ParentCatalog = cat
    End With
    tbl.Columns.Append col
Everything works fine up to this point.
When the next line executes, I receive a -2147217887 Multiple-step OLD DB operation generated errors.
    col.Properties("jet oledb:autogenerate").Value = True

This actually happens no matter what datatype I try to append or what Property I'm trying to set.
I've seen multiple examples of this same code all over the internet, but can't seem to get it to work.
Any help is greatly appreciated.

Answer : ADOX Add Column Multi-Step OLE DB errors

I notice in your original code that you call the "col.Properties("jet oledb:autogenerate").Value = True" AFTER you called the "tbl.Columns.Append". This is why you get the error.  You should initialize all field properties BEFORE appending the new field into the table.

I've test this on an existing table, and it worked fine.  You should try it.

Private Sub Command1_Click()
   CreateField "C:\Temp\db1.mdb", "tblTest", "RepIDTest"
End Sub

Private Sub CreateField(sDBPath As String, sTblName As String, sColName As String)

    Dim tbl As ADOX.Table
    Dim col As New ADOX.Column
    Dim cat As New ADOX.Catalog
    Dim cnn As New ADODB.Connection
   
    Set cnn = New ADODB.Connection
    cnn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
             "Data Source=" & sDBPath & ";"

    Set cat = New ADOX.Catalog
    Set cat.ActiveConnection = cnn
    Set tbl = cat.Tables(sTblName)
    Set col = New ADOX.Column

    With col
        .ParentCatalog = cat
        .Name = sColName
        .Type = adGUID
        .Properties("jet oledb:autogenerate").Value = True
    End With

    tbl.Columns.Append col

End Sub
Random Solutions  
 
programming4us programming4us