您现在的位置: 理想中国 > 教程 > 数 据 库 > ACCESS > 正文

以编程方式创建“自动编号”字段并将其“新值”属性设置为“随机” - 站长资讯

[ 来源:不详 | 作者:佚名 | 时间:2006-8-17 21:57:31 | 收藏本文 ] 【字体:
适用于
中级用户:要求具备基本的宏、编码和互操作技能。

本文仅适用于 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 方法
然后,单击搜索查看该主题。
文章录入:yixiaoer    责任编辑:yixiaoer 
发表评论
请自觉遵守互联网相关政策法规,不要恶意评论、广告和违禁词语。
昵称:
内容:
验证:
    评论表情(图片版权归悠嘻猴作者所有)



我要评论网友评论[只显示最新10条。评论内容只代表网友观点,与本站立场无关]

·用户发表意见仅代表其个人意见,并且承担一切因发表内容引起的纠纷和责任
·本站管理人员有权在不通知用户的情况下删除不符合规定的评论信息或留做证据
·请客观的评价您所看到的资讯,提倡就事论事,杜绝漫骂和人身攻击等不文明行为
·此图片和文章系本站搜索引擎全网蜘蛛程序自动抓取,由此图片和文章引起的各项法律问题,请与图片来源网站联系,本站与内容的出处无关。