热点推荐:ASP.Net | ADO.Net | VB.Net | Web服务器 | Access | MSSQL | MySQL | Oracle | .Net控件 | Win 9x | Win 2000 | Win 2003 | DOS | Unix | 注册表 | 应用其它 | 安装调试 | 基本操作 | 使用技巧 | 系统优化 |故障处理 | 个性风格 | 病毒安全 | 专杀工具
您现在的位置: 中华IT技术网 >> 数据库 >> ACCESS >> 正文
全文
以编程方式创建“自动编号”字段并将其“新值”属性设置为“随机”
作者:ylzxy580…    文章来源:不详    更新时间:2007-4-14
适用于
中级用户:要求具备基本的宏、编码和互操作技能。

本文仅适用于 Microsoft Access 数据库 (.mdb)。

概要

本文阐明如何以编程方式在 Microsoft Access 表中创建一个“自动编号”字段,并将该字段的新值属性设置为随机

更多信息

要以编程方式创建一个“自动编号”字段并将该字段的新值属性设置为随机,请按照下列步骤操作:
  1. 启动 Microsoft Access。
  2. 文件菜单上,单击新建。在新建文件任务窗格中,单击空数据库。键入该数据库的路径和文件名,然后单击创建
  3. 视图菜单上,指向数据库对象,然后单击模块。单击新建
  4. 将下面的示例代码键入到新模块中:
    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 方法
然后,单击搜索查看该主题。

  • 上一篇文章:
  • 下一篇文章:
  • 相关文章
    最新更新
    编辑推荐
    热门图片
    频道大全
    文章阅读排行
    周排行
    月排行