简体   繁体   中英

Cannot connect to sql server with VBA (Run-time error (80040e14))

I am trying to connect to my Sql database and get one simple recordset out of it running this code:

    Sub ConnectToSQL()

    Dim cnn As New ADODB.Connection
    Dim cmd As New ADODB.Command
    Dim rs As New ADODB.Recordset

    With cnn
         .ConnectionString = "File Name=C:\inetpub\tc\TEST.udl"
         .Open
    End With

    With cmd
          .ActiveConnection = cnn
          .CommandType = xlCmdSql
          .CommandText = "SELECT * FROM TEST"
    End With

    rs.Open cmd.Execute, cnn

    If Not rs.EOF Then
           Sheets(1).Range("A1").CopyFromRecordset rs
           rs.Close
    Else
           MsgBox "No records returned", vbCritical
    End If

    cn.Close
    Set cn = Nothing
    Set rs = Nothing

    End Sub

As a result I get the run-time error message (80040e14) What could be wrong here?

Thanks,

Do you want to try following?
Please do not forget to add Tools> Refernces if necessary.

Sub ConnectToSQL()    
    Dim cnn As ADODB.Connection
    Dim rs As New ADODB.Recordset
    Dim ConnectionString As String

     Set cnn = New ADODB.Connection

    ConnectionString = "File Name=C:\inetpub\tc\TEST.udl"

    cnn.Open ConnectionString
    cnn.CommandTimeout = 900

     strquery = "SELECT * FROM TEST;"

    'MsgBox strquery
    rs.Open strquery, cnn

    If Not rs.EOF Then
           Sheets(1).Range("A1").CopyFromRecordset rs
           rs.Close
    Else
           MsgBox "No records returned", vbCritical
    End If

    cnn.Close
    Set cnn = Nothing
    Set rs = Nothing
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM