无法使用VBA连接到sql server(运行时错误(80040e14))

时间:2016-06-14 15:05:20

标签: sql-server excel vba excel-vba

我正在尝试连接到我的Sql数据库,并从中运行此代码获取一个简单的记录集:

    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

结果我得到了运行时错误消息(80040e14)这里可能有什么问题?

谢谢,

1 个答案:

答案 0 :(得分:0)

你想试试吗?
请不要忘记添加工具>必要时参加。

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