作为替代方案,DoCmd.TransferSpreadsheet acLink, ...
您可以简单地“克隆”现有TableDef
对象,调整.SourceTableName
属性,并将更新的TableDef
对象替换为现有对象。这种方法的优点是可以保留现有文件位置、Excel 文档类型等,从而避免将这些值硬编码到DoCmd.TransferSpreadsheet
语句中的诱惑。
例如,我在 Access 中有一个名为 [LinkedTableInExcel] 的链接表,它指向OldSheetName
在 Excel 文档中命名的工作表。DCount()
我可以通过使用VBA 即时窗口中的表达式来验证链接表是否正常工作
?DCount("*","LinkedTableInExcel")
2
现在,如果我在 Excel 中打开文档并将工作表名称更改为NewSheetName
Access 中的链接表将停止工作
但是,我可以按如下方式更新链接表
Sub UpdateExcelLinkedTable()
Dim cdb As DAO.Database
Dim tbd As DAO.TableDef, tbdNew As DAO.TableDef
Dim n As Long
Const LinkedTableName = "LinkedTableInExcel"
Set cdb = CurrentDb
Set tbd = cdb.TableDefs(LinkedTableName)
Debug.Print "Current .SourceTableName is: " & tbd.SourceTableName
On Error Resume Next
n = DCount("*", LinkedTableName)
Debug.Print "The linked table is " & IIf(Err.Number = 0, "", "NOT ") & "working."
On Error GoTo 0
Set tbdNew = New DAO.TableDef
tbdNew.Name = tbd.Name
tbdNew.Connect = tbd.Connect
tbdNew.SourceTableName = "NewSheetName$"
Set tbd = Nothing
cdb.TableDefs.Delete LinkedTableName
cdb.TableDefs.Append tbdNew
Set tbdNew = Nothing
Set tbd = cdb.TableDefs(LinkedTableName)
Debug.Print "Updated .SourceTableName is: " & tbd.SourceTableName
On Error Resume Next
n = DCount("*", LinkedTableName)
Debug.Print "The linked table is " & IIf(Err.Number = 0, "", "NOT ") & "working."
On Error GoTo 0
Set tbd = Nothing
Set cdb = Nothing
End Sub
结果:
Current .SourceTableName is: OldSheetName$
The linked table is NOT working.
Updated .SourceTableName is: NewSheetName$
The linked table is working.