Ask Me Help Desk

Ask Me Help Desk (https://www.askmehelpdesk.com/forum.php)
-   Access (https://www.askmehelpdesk.com/forumdisplay.php?f=441)
-   -   Error in making primary key through VBA (https://www.askmehelpdesk.com/showthread.php?t=365445)

  • Jun 15, 2009, 09:07 PM
    cuuplate
    Error in making primary key through VBA
    I am trying to use VBA code to create a primary key index in an existing database. I am trying this code, but when it gets to the line tbl.Indexes.Append idx I always get the error: Invalid Field Definition idx1 in definition of index or relationship. What am I doing wrong?

    Private Sub Addkey_Click()
    On Error Go to ErrHandler

    Dim db As Database
    Dim tbl As TableDef
    Dim fld As DAO.Field
    Dim idx As DAO.Index

    Tablen = Me.tablenm

    Set db = CurrentDb()
    Set tbl = db.TableDefs(Tablen)
    Set idx = tbl.CreateIndex("Idx1")

    Set fld = idx.CreateField("idx1")
    idx.Fields.Append fld
    idx.Primary = True
    tbl.Indexes.Append idx

    CleanUp:

    Set fld = Nothing
    Set idx = Nothing
    Set tbl = Nothing
    Set db = Nothing

    Exit Sub

    ErrHandler:

    MsgBox "Error in Addkey( )." & vbCrLf & vbCrLf & _
    "Error #" & Err.Number & vbCrLf & vbCrLf & Err.Description
    Err.Clear
    Go to CleanUp
    End Sub
  • Jun 16, 2009, 06:13 AM
    ScottGem

    A Primary key is automatically indexed. You don't need to add an index if you set the field as a PK. Try commenting out the offending line and then check the table to see if the field has been designated as a PK.
  • Jun 16, 2009, 02:32 PM
    cuuplate
    Quote:

    Originally Posted by ScottGem View Post
    A Primary key is automatically indexed. You don't need to add an index if you set the field as a PK. Try commenting out the offending line and then check the table to see if the field has been designated as a PK.

    Unfortunately, when I comment out tbl.Indexes.Append idx nothing happens to the database.

  • All times are GMT -7. The time now is 08:47 PM.