用access做應(yīng)用程序,往往做成"數(shù)據(jù)"和"程序"兩個數(shù)據(jù)庫,"數(shù)據(jù)"數(shù)據(jù)庫中只存放數(shù)據(jù)表,"程序"數(shù)據(jù)庫中存放所有的form,query,report,module等,通過表聯(lián)接"程序"數(shù)據(jù)庫可以訪問所有"數(shù)據(jù)"數(shù)據(jù)庫中的表。
當(dāng)我們的應(yīng)用程序更換存儲位置的時候往往失去正確的表聯(lián)接,造成運(yùn)行錯誤。下面的一段程序可以自動找回表聯(lián)接。在我的應(yīng)用中"程序"數(shù)據(jù)庫名字是stockMgr.mdb,"數(shù)據(jù)"數(shù)據(jù)庫名字是stock-Data.mdb
注意: 該程序僅限于"程序"和"數(shù)據(jù)"存放在同一個目錄而且是對應(yīng)單個"數(shù)據(jù)"文件的情況。
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 & ",繼續(xù)嗎?", 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
在程序啟動或者按鈕動作中調(diào)用即可。
更多信息請查看IT技術(shù)專欄