用access做应用程序,往往做成"数据"和"程序"两个数据库,"数据"数据库中只存放数据表,"程序"数据库中存放所有的form,query,report,module等,通过表联接"程序"数据库可以访问所有"数据"数据库中的表。
当我们的应用程序更换存储位置的时候往往失去正确的表联接,造成运行错误。下面的一段程序可以自动找回表联接。在我的应用中"程序"数据库名字是stockMgr.mdb,"数据"数据库名字是stock-Data.mdb
注意:该程序仅限于"程序"和"数据"存放在同一个目录而且是对应单个"数据"文件的情况。
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
在程序启动或者按钮动作中调用即可。