通过ADOX添加带有自动编号主键的Access表

时间:2013-12-05 17:59:26

标签: ms-access ms-access-2007 access-vba

我正在尝试添加一个带有主键的新表,并希望将其“AutoIncrement”属性设置为True。这就是我在做的事情:

Dim cat As New ADOX.Catalog
Dim tbl As New ADOX.Table
Dim col As New ADOX.Column
Dim cnn As Object
Dim dbs As Database
Dim DataSource As String

DataSource = "\\spdb\depts\Msg_be.accdb"

Set cnn = CreateObject("ADODB.Connection")

cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0; " & _
  "Data Source=" & DataSource & ";Jet OLEDB:Database Password=psWrD; "

Set dbs = OpenDatabase(DataSource, False, False, "MS Access;PWD=psWrD")
cat.ActiveConnection = cnn

tbl.Name = "tblMsg"

tbl.Columns.Append "MsgID", adInteger
tbl.Keys.Append "PrimaryKey", adKeyPrimary, "MsgID"
tbl.Columns.Item("MsgID").Properties("AutoIncrement") = True
cat.Tables.Append tbl

然而,我收到此错误:

Run-time error '3265':
Item cannot be found in the collection corresponding to the requested name or ordinal.

在线:

tbl.Columns.Item("MsgID").Properties("AutoIncrement") = True

我在这里错过了什么吗?

2 个答案:

答案 0 :(得分:3)

以下代码,大量借鉴here,似乎可以解决问题:

Dim con As ADODB.Connection
Dim cat As ADOX.Catalog, tbl As ADOX.Table
Dim col As ADOX.Column, key As ADOX.key

Set con = New ADODB.Connection
con.Open _
        "Provider=Microsoft.ACE.OLEDB.12.0;" & _
        "Data Source=C:\Users\Public\Database1.accdb;"
Set cat = New ADOX.Catalog
cat.ActiveConnection = con

Set tbl = New ADOX.Table
tbl.Name = "tblMsg"
cat.Tables.Append tbl

Set col = New ADOX.Column
Set col.ParentCatalog = cat
col.Name = "MsgID"
col.Type = adInteger
col.Properties("AutoIncrement") = True
col.Properties("Seed") = CLng(1)
col.Properties("Increment") = CLng(1)
tbl.Columns.Append col

Set key = New ADOX.key
key.Name = "PRIMARY"
key.Type = adKeyPrimary
key.Columns.Append "MsgID"
tbl.Keys.Append key

关键点:

  • “AutoNumber-ness”是列(字段)的函数,而不是键。
  • 设置.ParentCatalog对象属性允许ADOX识别col是Access列,因此可以具有“AutoIncrement”,“Seed”和“Increment”属性,这三个属性组合在一起形成AutoNumber字段。

答案 1 :(得分:3)

您可以弄清楚如何修改ADOX方法以获得您想要的效果。但是,由于您可以打开与目标数据库的工作ADO连接,我认为使用该连接执行ALTER TABLE语句应该更简单,该语句将自动编号 MsgID 字段添加到您的表

我在Access 2007中测试了这种方法,并成功将自动编号字段添加到我的 tblMsg 表中。 (但是我必须改变ADO连接属性才能连接到我的db文件。)

Dim cnn As Object
Dim DataSource As String
Dim strSql As String

DataSource = "\\spdb\depts\Msg_be.accdb"
Set cnn = CreateObject("ADODB.Connection")

cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0; " & _
  "Data Source=" & DataSource & ";Jet OLEDB:Database Password=psWrD; "
strSql = "ALTER TABLE tblMsg ADD COLUMN MsgID COUNTER PRIMARY KEY;"
Debug.Print strSql
cnn.Execute strSql