Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to set primarykey to a field by VBA or Marco?

Status
Not open for further replies.
May 24, 2005
30
US
Could anyone tell me how to set primarykey to a field by VBA or Marco?
I need to update a table once a week, and I need Primarykey for that table.

Thanks
 
Hi
Do you mean (?):
Code:
Set db = CurrentDb
Set tdf = db.TableDefs("TableName")
For Each idx In tdf.Indexes
    If idx.Primary Then
        Debug.Print idx.Name
        Debug.Print idx.Fields
    End If
Next
 
for example, I want the table of "TblEmployee", the field of "EmployeeID" to be the PrimaryKey. just by clicking the command button. not by setup through design view of the table because I do not want everybody to touch the structure of the database.

Thanks

 
This might suit:
Code:
Set db = CurrentDb
Set tdf = db.TableDefs("tblEmployee")
'Create index
Set idxnew = tdf.CreateIndex("EmpID")
'Add fields for index
idxnew.Fields.Append idxnew.CreateField("EmployeeID")
'Primary key
idxnew.Primary = True
'Add index to indexes collection
tdf.Indexes.Append idxnew

For Each idx In tdf.Indexes
    If idx.Primary Then
        Debug.Print idx.Name
        Debug.Print idx.Fields
    End If
Next

This code will alter your table, if I have it right, if not, who knows what it will do? So you need a back up as I only tested lightly. :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top