如何使用VBA将Access表链接到SQL Server

Our*_*nas 4 sql-server ms-access vba linked-tables ms-access-2003

我正在尝试使用 SQL Server 后端在 Access 中创建链接(或导入)表。基本上,业务用户定期需要表的副本[SQL Rulesnew](是的,还有空格,叹气),因此我们想为他们提供一个 Access 2003 的小工具,可以按需完成这项工作。

我尝试过使用Docmd.TransferDataBase acTable但没有运气

这是我正在使用的代码:

Sub getData()

Dim sConnStr As String
Dim oTable As TableDef
Dim sDestinationTable As String
Dim dbs As Database
Dim tbl As DAO.TableDef
Dim tblLinked As DAO.TableDef       

    sDestinationTable = "SQL Rulesnew"
    Set dbs = CurrentDb

    ' source table name has a SPACE (rolleyes!)
    CurrentDb.CreateTableDef sDestinationTable  

    ' got the below from a Data Link File (UDL)
    sConnStr = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=MYDBNAME;Data Source=MYSERVERNAME"

    ' the below also failed!
    'DoCmd.TransferDatabase acLink, "ODBC Database", "ODBC;Driver={SQL Server};Server=Fos;Database=Hermes_Rep;Trusted_Connection=Yes", acTable, "[Report SQLRulesnew]", "SQLRules" & VBA.Format(Now, "ddmmyyyy")

    'If DCount("*", "MSysObjects", "[Name]='[SQL Rulesnew]' AND [Type] In (1, 4, 6)") > 0 Then
    If IsTable(sDestinationTable) Then
       DoCmd.DeleteObject acTable, sDestinationTable
    End If

    Set tblLinked = dbs.CreateTableDef(sDestinationTable)
    Debug.Print "Linking the " & sDestinationTable
    tblLinked.Connect = sConnStr
    tblLinked.SourceTableName = sDestinationTable
    dbs.TableDefs.Append tblLinked
    tblLinked.RefreshLink

End Sub

Function IsTable(sTblName As String) As Boolean
    'does table exists and work ?
    'note: finding the name in the TableDefs collection is not enough,
    '      since the backend might be invalid or missing
Dim x
    On Error GoTo Coventry
    x = DCount("*", sTblName)
    IsTable = True
    Exit Function

Coventry:
    Debug.Print Now, sTblName, Err.Number, Err.Description
    IsTable = False
End Function
Run Code Online (Sandbox Code Playgroud)

不幸的是,我收到一条错误消息:无法找到可安装的 ISAMdbs.TableDefs.Append tblLinked

我应该怎么办?

谢谢菲利普

Our*_*nas 6

我通过反复试验找到了答案......

基本上,我在 Access 中的表名称可以有一个空格,而不使用[方括号],因此以下命令可以正常工作(删除任何现有对象后):

DoCmd.TransferDatabase _
  acImport, _
  "ODBC Database", _
  "ODBC;Driver={SQL Server};Server=Fos;Database=Hermes;Trusted_Connection=Yes", _
  acTable, _
  "sourceTable", _
  "targetTable"
Run Code Online (Sandbox Code Playgroud)