我在ms-access中有一个链接表,该表链接到一个sql server表,当我试图通过VBA从ms-access链接表中获取excel中的数据时,显示错误消息“ ODBC连接失败”。
注意:-我可以手动成功刷新ms-access中的ms-access链接表,“ peoplemain”是链接表的名称。
注意:-当我尝试从非链接表中获取数据时,该数据已成功运行。
下面的代码适用于Excel-32位版本,但不适用于excel-64位版本。
[代码]
Sub FetchData()
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim conn As String
conn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=G:\Workflow Tools (Michael Cantor)\Tool For Fixing Bug From Michael Cantor\PI MDT Reconciliation Workflow Tool\SampleforPractice.accdb;"
Set cn = New ADODB.Connection
Set rs = New ADODB.Recordset
cn.Open conn
rs.Open "Select * from peoplemain", cn 'Error Line
Sheet1.Range("A1").CopyFromRecordset rs
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
谢谢
Kashif
答案 0 :(得分:0)
我会尝试将strSQL
设置为这样的字符串(我遇到了与您相同的问题,并且在进行更改时它对我有用):
Sub FetchData()
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim conn As String, strSQL AS String
conn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=G:\Workflow Tools (Michael Cantor)\Tool For Fixing Bug From Michael Cantor\PI MDT Reconciliation Workflow Tool\SampleforPractice.accdb;"
strSQL = "Select * from peoplemain"
Set cn = New ADODB.Connection
Set rs = New ADODB.Recordset
cn.Open conn
rs.Open strSQL , cn 'Error Line
Sheet1.Range("A1").CopyFromRecordset rs
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub