3

我正在尝试使用以下代码在 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)
4

2 回答 2

2

Remou 向我指出了另一个连接字符串的方向,但我仍然得到了相同的结果。我用谷歌搜索了一下,并想出了另一个具有不同实现的 SO Question 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)
于 2012-08-13T14:44:04.387 回答
0

那不是您需要的连接字符串。它应该是这样的:

Provider=sqloledb;Data Source=SERVER\SERVER;Initial Catalog=cs_db;Integrated Security=SSPI;

请参阅http://connectionstrings.com

于 2012-08-08T16:23:16.323 回答