在 Access 應用程式中,若需將現有的連結資料表重新指向 SQL Server,可撰寫 VBA 函式 relink() 透過檔案 DSN 連接字串批次更新所有連結資料表的連線資訊。以下提供完整程式碼與關鍵參數說明。
Function relink()
Dim db As Database
Dim tbl As TableDef
Dim a As String
Dim b As String
Dim d As String
a = "sa" ' 資料庫用戶
b = "abc" ' 資料庫密碼
d = "abcde" ' 資料庫名稱
Set db = CurrentDb
For Each tbl In db.TableDefs
If tbl.Attributes = 536870912 Then ' 判斷是否為連結資料表
tbl.Connect = "FILEDSN=d:\demo\steel.dsn;UID=" & a & ";PWD=" & b & ";WSID=;DATABASE=" & d & ";Network=DBMSSOCN"
tbl.Attributes = dbAttachSavePWD
tbl.RefreshLink
End If
Next
End Function
d:\demo\steel.dsn)。a 提供。b 提供。d 提供。執行此函式後,所有屬性為 536870912(連結資料表)的 TableDef 將自動更新連線字串並重新整理連結,即可無縫切換至指定的 SQL Server 執行個體與資料庫。