在TableDefs.Append上创建表时显示Invalid Argument时出错

时间:2017-03-16 16:36:46

标签: vba access

我正在Access 2013中编写一个程序。如果是第一次安装程序,它将创建一个外部数据库(稍后将链接)并创建所需的表。在附加的代码中,我正在运行一个数组,该数组包含所需的所有表的列表,并使用具有与特定表关联的所有字段的内部(本地)表。它运行代码并创建所有字段就好了,但是一旦它到达db1.TableDefs.Append newTable行就会抛出Invalid Argument错误。我尽可能多地搜索,看起来我的设置和其他设置一样,无法弄清问题是什么。

Function CreateDataTables()
Dim db As Database
Dim db1 As Database
Dim rst As Recordset
Dim tblCount As Integer
Dim rst1 As Recordset
Dim newTable As TableDef
Dim newField As Field
Dim newIdx As Index
Dim newType As Variant
Dim newLength As Variant
Dim newPK As String
Dim sysTable As String
Dim SQLstr As String
Dim x As Integer
Dim tblNames() As Variant
Stop

SQLstr = "SELECT DISTINCT tableName "
SQLstr = SQLstr + "FROM sysdata;"

Set db = DBEngine(0)(0)
Set rst = db.OpenRecordset(SQLstr, dbOpenSnapshot, dbSeeChanges)
tblCount = rst.RecordCount
'Creating array to house table names
ReDim tblNames(tblCount)
tblNames() = rst.GetRows(tblCount)

Set db = Nothing
Set rst = Nothing

Set db = DBEngine(0)(0)
Set rst = db.OpenRecordset("sysdata", dbOpenSnapshot, dbSeeChanges)
'Create database reference to newly created database in prior function
Set db1 = OpenDatabase(dbFileLoc)

For x = 1 To tblCount
    'Create new tabledef
    Set newTable = db1.CreateTableDef(tblNames(0, (x - 1)))
    'Loop through each record of particular table (named in rst) to create each field
    Do While rst.Fields("tableName") = tblNames(0, (x - 1))
        newType = rst.Fields("typeData")
        newLength = rst.Fields("lengthField")
        newPK = Nz(rst.Fields("PKey"), "No")
        Set newField = newTable.CreateField(rst.Fields("fieldName"))
        With newField
            .Type = newType
            If Not IsNull(newLength) Then .Size = newLength
            'If field is indicated as a PK, this will create the PK
            If newPK = "Yes" Then
                With newTable
                    newField.Attributes = dbAutoIncrField
                    Set newIdx = .CreateIndex("PrimaryKey")
                    newIdx.Fields.Append newIdx.CreateField(tblNames(0, (x - 1)))
                    newIdx.Primary = True
                    .Indexes.Append newIdx
                End With
            End If
        End With
        'Append field
        newTable.Fields.Append newField

        rst.MoveNext
        If rst.EOF Then Exit Do
    Loop
    MsgBox "Table " + newTable.NAME + " create", vbOKOnly  'Placed to verify loop was completed and showing table name
    '''The line below gives the Invalid Argument error
    '''Do not know what is causing this
    db1.TableDefs.Append newTable
    db1.TableDefs.Refresh
Next

1 个答案:

答案 0 :(得分:0)

我终于弄清楚我的sysdata表中指定字段类型的数字是错误的。我甚至从MSDN站点获得了这个。我经历了一个循环来确定数据类型的实际数量,然后将它们放在表中并且它有效!我还在代码中找到了与主键有关的另一个错误。在我附加索引的地方,在CreateField中我有表名而不是字段名。一旦我改变了它,PK就会填充它。