David's post says...
Using DAO
The following code is slightly more long winded, but crucially it allows you to set the key field(s) in code:
Expand|Select|Wrap|Line Numbers
- ' we will need to create this table using DAO
- Dim tdf As DAO.TableDef
- ' Some variable to make the code more generic
- Dim strConnectionString As String
- Dim strNameInAccess As String
- Dim strNameInSQLServer As String
- Dim strKey As String
- ' set the connection string
- strConnectionString = _
- "ODBC;DRIVER=SQL Server; " & _
- "SERVER=.\SQLExpress;DATABASE=MyDatabase;Trusted_Connection=Yes"
- ' specify the tables you want to link. The table can be
- ' known by a different name in Access than the name in SQL server
- strNameInAccess = "tblYacht"
- strNameInSQLServer = "tblSailingBoat"
- ' specify the key field
- strKey = "SailingBoatID"
- ' Delete the table from the local database if it exists
- On Error Resume Next
- DoCmd.RunSQL "drop table " & strNameInAccess
- On Error GoTo 0
- ' Create a table using DAO give it a name in Access.
- ' Connect it to the SQL Server database.
- ' Say which table it links to in SQL Server.
- Set tdf = CurrentDb.CreateTableDef(strNameInAccess)
- tdf.Connect = strConnectionString
- tdf.SourceTableName = strNameInSQLServer
- ' Add this table Definition to the collection
- ' of Access tables
- CurrentDb.TableDefs.Append tdf
- ' Now create a unique key for this table by
- ' running this SQL
- On Error Resume Next
- DoCmd.RunSQL _
- "CREATE UNIQUE INDEX UniqueIndex ON " _
- & strNameInAccess & " (" & strKey & ")"
- On Error GoTo 0