我有一个过程,它重新链接数据库中的所有表,而不管它们是否是链接表。目前,这被设置为自动运行,因为它在调用该函数的AutoExec宏中设置。
代码有效但仅在关闭数据库并重新打开时才有效。我知道这是因为需要这样才能使新链接生效但是还是有这个吗?或者,如果不这样做,最好让VBA代码关闭数据库并重新打开它吗?
提前感谢您的反馈
P.S。这是代码,万一你好奇:
'*******************************************************************
'* This module refreshes the links to any linked tables *
'*******************************************************************
'Procedure to relink tables from the Common Access Database
Public Function RefreshTableLinks() As String
On Error GoTo ErrHandler
Dim strEnvironment As String
strEnvironment = GetEnvironment
Dim db As DAO.Database
Dim tdf As DAO.TableDef
Dim strCon As String
Dim strBackEnd As String
Dim strMsg As String
Dim intErrorCount As Integer
Set db = CurrentDb
'Loop through the TableDefs Collection.
For Each tdf In db.TableDefs
'Verify the table is a linked table.
If Left$(tdf.Connect, 10) = ";DATABASE=" Then
'Get the existing Connection String.
strCon = Nz(tdf.Connect, "")
'Get the name of the back-end database using String Functions.
strBackEnd = Right$(strCon, (Len(strCon) - (InStrRev(strCon, "\") - 1)))
'Debug.Print strBackEnd
'Verify we have a value for the back-end
If Len(strBackEnd & "") > 0 Then
'Set a reference to the TableDef Object.
Set tdf = db.TableDefs(tdf.Name)
If strBackEnd = "\Common Shares_Data.mdb" Or strBackEnd = "\Adverse Events.mdb" Then
'Build the new Connection Property Value - below needs to be changed to a constant
tdf.Connect = ";DATABASE=" & strEnvironment & strBackEnd
Else
tdf.Connect = ";DATABASE=" & CurrentProject.Path & strBackEnd
End If
'Refresh the table links
tdf.RefreshLink
End If
End If
Next tdf
ErrHandler:
If Err.Number <> 0 Then
'Create a message box with the error number and description
MsgBox ("Error Number: " & Err.Number & vbCrLf & _
"Error Description: " & Err.Description & vbCrLf)
End If
End Function
修改
继Gords评论后,我添加了宏AutoExec
方法来调用下面的代码。有人看到这个问题吗?
Action: RunCode
Function Name: RefreshTableLinks()
答案 0 :(得分:5)
在这种情况下最常见的错误是忘记了.RefreshLink
TableDef但你已经这样做了。我刚刚测试了以下VBA代码,该代码在两个Access后端文件之间切换名为[Products_linked]的链接表:Products_EN.accdb
(英语)和Products_FR.accdb
(法语)。如果我运行VBA代码,然后立即打开链接表,我看到发生了变化;我不必关闭并重新打开数据库。
Function ToggleLinkTest()
Dim cdb As DAO.Database, tbd As DAO.TableDef
Set cdb = CurrentDb
Set tbd = cdb.TableDefs("Products_linked")
If tbd.Connect Like "*_EN*" Then
tbd.Connect = Replace(tbd.Connect, "_EN", "_FR", 1, 1, vbBinaryCompare)
Else
tbd.Connect = Replace(tbd.Connect, "_FR", "_EN", 1, 1, vbBinaryCompare)
End If
tbd.RefreshLink
Set tbd = Nothing
Set cdb = Nothing
End Function
我甚至测试过从AutoExec宏调用该代码,它似乎也按预期工作。
您可以尝试的一件事是在日常工作结束时立即致电db.TableDefs.Refresh
,看看是否有帮助。
这里的问题是数据库的“应用程序选项”中指定了“显示表单”,并且该表单显然会在 运行AutoExec宏之前自动打开 。将重新链接代码的函数调用移动到该“启动表单”的Form_Load事件处理程序似乎可能已得到解决。