我正在尝试使用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
很遗憾我收到错误在dbs.TableDefs.Append tblLinked
我该怎么办?
感谢 菲利普
答案 0 :(得分:3)
我通过反复试验找到答案......
基本上我在Access中的表名可以有一个空格而不使用 [方括号] , 所以下面的命令工作正常(删除任何现有的对象后):
DoCmd.TransferDatabase _
acImport, _
"ODBC Database", _
"ODBC;Driver={SQL Server};Server=Fos;Database=Hermes;Trusted_Connection=Yes", _
acTable, _
"sourceTable", _
"targetTable"