Excel VBA: ODBC SQL server driver query timeout expired

后端 未结 3 1913
轻奢々
轻奢々 2021-01-29 01:47

I have the below VBA query used in Excel 2016 that exacutes a MS Sql stored procedure, sometimes it executes smoothly and returns the recordset, but more often I get an error

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-29 02:26

    After weeks of testing various code changes, we found that when changing the SQL call to QueryTable method instead of CopyFromRecordset method, it is working fine.

    So I am pasting the code if anyone needs it in future.

    Sub GetDataset3()
    
    Dim cn As ADODB.Connection
    Dim Rs As ADODB.Recordset
    Dim UID, PWD, SRV As String
    UID = "userId"
    PWD = "passworD"
    SRV = "192.168.1.1"
    
    If Sheets("data").QueryTables.Count = 0 Then
         Sheets("data").Cells.Select
         Selection.ClearContents
    
         Dim Str As String 'adds backround query
         Str = ""
         For Each cell In Range("A1:A10").Cells
         Str = Str & Chr(10) & cell
        Next
    
          With Sheets("data").QueryTables.Add(Connection:="ODBC;UID=;PWD=;DRIVER=SQL 
            Server;SERVER=SRV", Destination:=Range("a2"))
            .CommandText = "select 1"
            'BackgroundQuery = True
            '.Refresh BackgroundQuery = True
            .FieldNames = False
            .AdjustColumnWidth = False
          End With
    End If
    
     With Sheets("data").QueryTables(1)
       .Connection = "ODBC;DRIVER=SQL Server;SERVER=" & SRV & 
       ";database=myDatabaseName;UID=" & UID & ";Pwd=" & PWD & 
       ";Trusted_Connection=no;APP=Microsoft Office"
       .CommandText = ("Get_dataset2 '" & Range("dateFrom") & "' ,'" & 
        Range("dateTo") & "' ")
        BackgroundQuery = True
        .Refresh BackgroundQuery:=False
    
     End With
    
    End Sub
    

提交回复
热议问题