在實際的應用中,Access做應用程序時,經常會做成"數據"和"程序"兩個數據庫,"數據"數據庫中只存放數據表,"程序"數據庫中存放所有的form,query,report,module等,通過表聯接"程序"數據庫可以訪問所有"數據"數據庫中的表。
當使用的應用程序更換存儲位置的時候往往失去正確的表聯接,造成運行錯誤。下面的一段程序可以自動找回表聯接。在我的應用中"程序"數據庫名字是stockMgr.mdb,"數據"數據庫名字是stock-Data.mdb
注釋:
(1)程序僅限於"程序"和"數據"存放在同一個目錄而且是對應單個"數據"文件的情況。
(2)在程序啟動或按鈕動作中調用即可。
以下為引用的內容:
Function ReAttachTable()
Dim MyDB As Database, MyTbl As TableDef
Dim cpath As String
Dim datafiles As String, i As Integer
On Error Resume Next
Set MyDB = CurrentDb
cpath = trimFileName(CurrentDb.Name)
datafiles = "stock-data.mdb"
DoCmd.Hourglass True
For i = 0 To MyDB.TableDefs.Count - 1
Set MyTbl = MyDB.TableDefs(i)
If MyTbl.Attributes = DB_ATTACHEDTABLE And Left(MyTbl.Connect, 1) = ";" Then
MyTbl.Connect = ";DATABASE=" & cpath & datafiles
MyTbl.RefreshLink
If Err Then
If vbNo = MsgBox(Err.description & ",繼續嗎?", vbYesNo) Then Exit For
End If
End If
Next i
DoCmd.Hourglass False
msgbox "Tables relink finish."
End Function
'絕對路徑中去掉文件名,返回路徑
Function trimFileName(fullname As String) As String
Dim slen As Long, i As Long
slen = Len(fullname)
For i = slen To 1 Step -1
If Mid(fullname, i, 1) = "/" Then
Exit For
End If
Next
trimFileName = Left(fullname, i)
End Function