VBA超时过期错误?

时间:2018-02-15 21:09:36

标签: excel vba excel-vba

  

运行一段时间后的以下查询显示"超时过期错误"。我甚至设置了" cmd.CommandTimeout = 3600",但在运行1分钟后,我得到"超时失效"

Sub ConnectSqlServer()

        Dim conn As ADODB.Connection
        Dim rs As ADODB.Recordset
        Dim sConnString As String
        Dim cmd As New ADODB.Command
        ' Create the connection string.
        sConnString = "Provider=SQLOLEDB;Data Source=server1;" & _
                      "Initial Catalog=database1;" & _
                      "Integrated Security=SSPI;"


         cmd.ActiveConnection = conn
        ' Create the Connection and Recordset objects.
        Set conn = New ADODB.Connection
        Set rs = New ADODB.Recordset

        cmd.CommandTimeout = 3600
        ' Open the connection and execute.
        conn.Open sConnString
        Set rs = conn.Execute("select column1, column2 from table1;")

        ' Check we have data.
        If Not rs.EOF Then
            ' Transfer result.
            Sheets(1).Range("A8").CopyFromRecordset rs
        ' Close the recordset
            rs.Close
        Else
            MsgBox "Error: No records returned.", vbCritical

        End If

        End Sub
  

请告诉我代码中需要更改的内容,以使其长时间运行并显示结果。

1 个答案:

答案 0 :(得分:1)

所以答案是两个人。

如评论中所述,在Connection对象

上设置它

要有更长的时间将其设置为0.最初看起来有点反直觉。

Connection.CommandTimeout = 0 

我之前已经运行过这些查询。

这里也有讨论:

ADODB query timeout