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