适用于
中级用户:要求具备基本的宏、编码和互操作技能。
本文仅适用于 Microsoft Access 数据库 (.mdb)。
概要
本文阐明如何以编程方式在 Microsoft Access 表中创建一个“自动编号”字段,并将该字段的新值属性设置为随机。
更多信息
要以编程方式创建一个“自动编号”字段并将该字段的新值属性设置为随机,请按照下列步骤操作:
启动 Microsoft Access。
在文件菜单上,单击新建。在新建文件任务窗格中,单击空数据库。键入该数据库的路径和文件名,然后单击创建。
在视图菜单上,指向数据库对象,然后单击模块。单击新建。
将下面的示例代码键入到新模块中:
Sub CreateRandomAutonumber()
' Create database, tabledef, and field objects.
Dim db As DAO.Database
Dim td As DAO.TableDef
Dim f As DAO.Field
' Set the database object to the current database.
' Set the tabledef object to a new table named Table1.
' Set the f (field) object to a new field in Table1 named MyAutoNumber.
Set db = CurrentDb
Set td = db.CreateTableDef("Table1")
Set f = td.CreateField("MyAutoNumber")
' Set the type and auto-increment properties for the Table1 field named
' MyAutoNumber.
f.Type = dbLong
f.Attributes = dbAutoIncrField
' Append the MyAutoNumber field to Table1.
td.Fields.Append f
' Create a new text field in Table1.
Set f = td.CreateField("MyTextField")
' Set the type property for MyTextField.
f.Type = dbText
' Append the MyTextField field to Table1.
td.Fields.Append f
' Append the Table1 tabledef to the database.
db.TableDefs.Append td
' Set the default value for MyAutoNumber to a random number function.
td.Fields("MyAutoNumber").DefaultValue = "GenUniqueID()"
' Refresh the database window.
Application.RefreshDatabaseWindow
End Sub
此示例代码将执行以下任务:
将字段的 Type 属性设置为 dbLong,并将字段的 Attributes 属性设置为 dbAutoIncrField。
将新的 TableDef 追加到 TableDefs 集合中。
将字段的 DefaultValue 属性设置为 GenUniqueID()。
参考
有关本文中使用的方法的更多信息,请在 Visual Basic 编辑器中,单击帮助菜单中的 Microsoft Visual Basic 帮助,在 Office 应答向导助理中键入下列主题之一:
createtabledef 方法
createfield 方法
append 方法
以编程方式创建“自动编号”字段并将其“新值”属性设置为“随机”
原创文章如转载,请注明:转载自悠悠博客 [ http://www.ajaxstu.com/ ]
相关文章:
- asp中使用access的系统表的方法(2007-5-10 4:29:56)
- Access2000数据库80万记录通用快速分页类(2007-5-1 1:9:19)
- ASP+ACCESS 无限级目录树(2006-9-14 3:42:5)
- 论ACCESS的性能(2006-8-22 6:51:31)
- 判断access数据库中某个表是否存在(2006-3-2 7:58:46)
- Access数据库的存储上限(2006-1-1 4:50:28)
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。
