primary key in VBA (1 Viewer)

Geordie2008

Registered User.
Local time
Today, 14:00
Joined
Mar 25, 2008
Messages
177
Guys,

I make a table using VBA, and I want to put a primary key on a field using code

Any ideas? Ive trawled the web with no joy.

M :)
 

Geordie2008

Registered User.
Local time
Today, 14:00
Joined
Mar 25, 2008
Messages
177
Hi,

Just to give a bit more background.... coz I really cant find an answer to this one anywhere on the web....

I am trying to add a primary key to a table that already exists using VBA or SQL code....

Tnx,
M
 

KenHigg

Registered User
Local time
Today, 09:00
Joined
Jun 9, 2004
Messages
13,327
With your dao table def object create a new index and set it's primary property to true.
 

Geordie2008

Registered User.
Local time
Today, 14:00
Joined
Mar 25, 2008
Messages
177
Do you have the exact code for this? Ive tried and tried and cannot get any code that actually does this?

M
 

KenHigg

Registered User
Local time
Today, 09:00
Joined
Jun 9, 2004
Messages
13,327
Give me a few minutes and I'll see if I can come up with a sample db...
 

grendell2099

Registered User.
Local time
Today, 06:00
Joined
Aug 9, 2006
Messages
29
Not to steal your thunder Ken, but might this be the sort of thing you are looking for? Supply the table name and name of your index field, it returns the next number.

Function GetTableIndex(GetTable As String, GetField As String) As Integer
'DATE: 04-17-08
'PURPOSE: get index number for a new record from the selected table & field
'NOTE: Function returns an integer
'YOU MAY USE THIS CODE, BUT YOU MUST CREDIT THE AUTHOR

'On Error GoTo ERR_HNDL

'DEFINE VARIABLES
'THIS MODULE CREATES THE INDEX NUMBER FOR NEW PTRs
Dim zst As DAO.Recordset 'TABLE CALLED FOR
Dim ErrorMessage As String 'for error reporting
'
'****************************************************************************************

Set zst = db.OpenRecordset(GetTable)

GetTableIndex = Nz(DMax("[" & GetField & "]", GetTable) + 1, 0)

'-----------------------------------------------------------------------------------
EXIT_SUB: 'CLEAR VARIABLES
zst.Close
Set zst = Nothing
DoCmd.SetWarnings True
ErrorMessage = ""
Exit Function

ERR_HNDL:
ErrorMessage = "Function GetTableIndex" & vbCr & "ERROR# " & Err.Number & vbCr & Err.Description
Call PlayMySound("fault.wav", SND_ASYNC) 'SND_SYNC) SND_LOOP)
Call ErrorReport(ErrorMessage)
Resume EXIT_SUB

End Function
 

DJkarl

Registered User.
Local time
Today, 08:00
Joined
Mar 16, 2007
Messages
1,028
The easiest way in code to add a primary key that I've found is to use SQL

Currentdb.Execute "ALTER TABLE [ExampleTable] ADD CONSTRAINT PrimaryKey PRIMARY KEY ( [FieldName1],[FieldName2] );"
 

Users who are viewing this thread

Top Bottom