我正在尝试使用以下代码在Excel中的SQL Server上打开记录集,但出现3709 - The connection cannot be used to perform this operation. It is either closed or invalid in this context.
错误。我哪里错了?:
编辑:
现在正在运行,我将更新以下代码:
'Declare variables'
Set objMyConn = New ADODB.Connection
Set objMyRecordset = New ADODB.Recordset
Dim strSQL As String
'Open Connection'
objMyConn.ConnectionString = "Driver={SQL Server};Server=SERVER\SERVER; Database=we_ci_db; Trusted_Connection=Yes"
objMyConn.Open
'Set and Excecute SQL Command'
strSQL = "select * from tblUsers"
'Open Recordset'
Set objMyRecordset.ActiveConnection = objMyConn
objMyRecordset.Open strSQL
'Copy Data to Excel'
ActiveSheet.Range("A1").CopyFromRecordset (objMyRecordset)
答案 0 :(得分:2)
Remou指出我在另一个连接字符串的方向,但我仍然得到相同的结果。我用谷歌搜索了一下,然后提出了另一个SO问题LINK,其中有不同的实现,结果是:
'Declare variables'
Set objMyConn = New ADODB.Connection
Set objMyRecordset = New ADODB.Recordset
Dim strSQL As String
'Open Connection'
objMyConn.ConnectionString = "Driver={SQL Server};Server=SERVER\SERVER; Database=we_ci_db; Trusted_Connection=Yes"
objMyConn.Open
'Set and Excecute SQL Command'
strSQL = "select * from tblUsers"
'Open Recordset'
Set objMyRecordset.ActiveConnection = objMyConn
objMyRecordset.Open strSQL
'Copy Data to Excel'
ActiveSheet.Range("A1").CopyFromRecordset (objMyRecordset)
答案 1 :(得分:0)
这不是您需要的连接字符串。它应该是这样的:
Provider=sqloledb;Data Source=SERVER\SERVER;Initial Catalog=cs_db;Integrated Security=SSPI;