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