如何使用VBA for MS Access在预先存在的表中创建字段?

时间:2016-07-18 17:53:45

标签: vba ms-access access-vba ms-access-2010

我有一个数据库Database和一个表Table。我在网上找到了如何从MS Access中的VBA中新创建的数据库和表创建字段,但是在运行宏之前数据库和表已经存在时,我不知道如何执行此操作。

要在没有预先存在的数据库和表的情况下执行此操作,我可以运行以下命令:

Sub CreateTable()

    Dim db As DAO.Database
    Dim table1 As DAO.TableDef

    Set db = CurrentDb

    Set table1 = db.CreateTableDef("ExampleTable")

    With table1
        .Fields.Append.CreateField("newField", String)
    End With

但是我怎样才能调整它以将相同的字段添加到预先存在的表中?

或者更具体地说,我该如何修改

Set table1 = db.CreateTableDef("ExampleTable")

这样table1指向db数据库中的现有表?

2 个答案:

答案 0 :(得分:5)

您可以通过执行Access DDL语句向现有表添加字段。

Dim strDdl As String
strDdl = "ALTER TABLE ExampleTable ADD COLUMN newField TEXT(255);"
CurrentProject.Connection.Execute strDdl

TEXT(255)中,255是字段大小---字段可以包含的最大字符数。 255是Access文本字段的绝对上限。从TEXT方法创建ADODB.Connection.Execute字段时,您必须包含字段大小的值。如果您愿意,请选择较小的值。

使用DAO方法创建新字段时,如您的问题所示,文本字段的字段大小是可选的。但是,如果未指定大小,Access将使用“访问”选项中的“默认文本字段大小”设置。

答案 1 :(得分:3)

像这样的东西。只需引用TableDefs集合中的表名,而不是创建一个。

Public Sub CreateTable()

Dim table1 As DAO.TableDef
Dim fld As DAO.Field
Dim tdf As DAO.TableDef

' Create the new Table Def object
Set table1 = New DAO.TableDef

' Name the Table
table1.Name = "Test"

' Create the new Field
Set fld = New DAO.Field
fld.Name = "newField"
fld.Type = DataTypeEnum.dbText

' Append the Field to the table
table1.Fields.Append fld

' Append the table to the Table Def Collection
' Without this the table just lives in memory
CurrentDb.TableDefs.Append table1

' Create another Field
Set fld = New DAO.Field
fld.Name = "newField2"
fld.Type = DataTypeEnum.dbText

' Append the New Field to the EXISTING table
CurrentDb.TableDefs("Test").Fields.Append fld

End Sub