如何用VBA创建子表 并重命名子表
时间: 2024-03-27 15:36:20 浏览: 101
可以通过以下VBA代码创建一个子表并重命名它:
```
Sub CreateSubTable()
Dim db As DAO.Database
Dim tdf As DAO.TableDef
Dim fld As DAO.Field
Dim idx As DAO.Index
Dim rel As DAO.Relation
Dim strTableName As String
Dim strFieldName As String
' Set table and field names
strTableName = "MainTable"
strFieldName = "SubTableID"
' Open database
Set db = CurrentDb
' Create subtable
Set tdf = db.CreateTableDef(strTableName & "_" & strFieldName)
' Add fields to subtable
Set fld = tdf.CreateField(strFieldName, dbLong)
tdf.Fields.Append fld
' Add index to subtable
Set idx = tdf.CreateIndex("PrimaryKey")
idx.Primary = True
idx.Fields.Append fld
tdf.Indexes.Append idx
' Append subtable to database
db.TableDefs.Append tdf
' Create relationship between main table and subtable
Set rel = db.CreateRelation("MainTable_SubTable", strTableName, strTableName & "_" & strFieldName)
rel.Fields.Append rel.CreateField(strFieldName)
rel.ForeignTable = strTableName
rel.Attributes = dbRelationDeleteCascade
db.Relations.Append rel
' Rename subtable
tdf.Name = "NewSubTableName"
End Sub
```
这段代码会在当前数据库中创建一个名为"MainTable_SubTableID"的子表,包含一个名为"SubTableID"的字段,并且将子表重命名为"NewSubTableName"。请根据自己的需要修改表名和字段名。
阅读全文