Dim CurrentDatabase As Database
Dim MyTableDef As TableDef
' Open the Microsoft Access database named Test.mdb.
Set CurrentDatabase = DBEngine.Workspaces(0).OpenDatabase _
("C:\Access\Data\Test.mdb")
' Create the TableDef object.
Set MyTableDef = CurrentDatabase.CreateTableDef("Attached SQL Server Table")
' Set the connection information.
MyTableDef.Connect = "ODBC;DATABASE=AR;UID=saWD=nimda;DSN=SQLTEST"
MyTableDef.SourceTableName = "Accounts"
' Append the TableDef object to create the link.
CurrentDatabase.TableDefs.Append MyTableDef
' Display a confirmation message.
MsgBox "Finished attaching " & MyTableDef.SourceTableName & ".", 0
開啟ODBC Data Source的資料表
以下範例是在無法連結外部資料時,教導您如何直接開啟Microsoft SQL Server資料表,而後開啟資料表上的 Recordset。
警告:相對於連結,直接開啟ODBC資料是非常沒有效率的並且嚴重拖垮效能,儘可能使用連結資料表。
Dim CurrentDatabase As Database
Dim MySet As Recordset
' Open the external SQL Server database named AP.
' ***NOTE THAT PERFORMANCE USING THE DATABASE WILL BE SLOW.***
Set CurrentDatabase = DBEngine.Workspaces(0).OpenDatabase _
("", False,False, "ODBC;DATABASE=AP;UID=MyIDWD=whocares;DSN=SQLSERV")
' Open a Recordset object on the Accounts table.
Set MySet = CurrentDatabase.OpenRecordset("Accounts")