总是使用VBA获得“连接失败”连接sqlserver

时间:2018-11-30 02:07:06

标签: excel vba excel-vba office365 officedev

我正在尝试从VBA程序连接sqlserver,我参考以下代码来实现它,但是我 有问题:连接失败。任何帮助。预先谢谢你。

代码:

Sub ADOExcelSQLServer()
     ' Carl SQL Server Connection
     '
     ' FOR THIS CODE TO WORK
     ' In VBE you need to go Tools References and check Microsoft Active X 
    'Data Objects 2.x library

Dim Cn As ADODB.Connection
Dim Server_Name As String
Dim Database_Name As String
Dim User_ID As String
Dim Password As String
Dim SQLStr As String
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset

Server_Name = "EXCEL-PC\EXCELDEVELOPER" ' Enter your server name here
Database_Name = "AdventureWorksLT2012" ' Enter your database name here
User_ID = "" ' enter your user ID here
Password = "" ' Enter your password here
SQLStr = "SELECT * FROM [SalesLT].[Customer]" ' Enter your SQL here

Set Cn = New ADODB.Connection
Cn.Open "Driver={SQL Server};Server=" & Server_Name & ";Database=" & Database_Name & _
";Uid=" & User_ID & ";Pwd=" & Password & ";"

rs.Open SQLStr, Cn, adOpenStatic
 ' Dump to spreadsheet
With Worksheets("sheet1").Range("a1:z500") ' Enter your sheet name and range here
    .ClearContents
    .CopyFromRecordset rs
End With
 '            Tidy up
rs.Close
Set rs = Nothing
Cn.Close
Set Cn = Nothing
End Sub

2 个答案:

答案 0 :(得分:0)

测试一下。

Sub cn()
    Dim con As New ADODB.Connection
    Dim cmd As New ADODB.Command
    Dim rst As New ADODB.Recordset
    Dim i As Integer

    con.ConnectionString = "Provider=SQLOLEDB.1;" _
             & "Server=(local);" _
             & "Database=AdventureWorksLT2012;" _
             & "Integrated Security=SSPI;" _
             & "DataTypeCompatibility=80;"

    con.Open


    Set cmd.ActiveConnection = con
    cmd.CommandText = "SELECT * FROM [SalesLT].[Customer]"
    Set rst = cmd.Execute
    Range("A1").CopyFromRecordset rst

    con.Close
    Set con = Nothing

End Sub

答案 1 :(得分:0)

我检查了您的代码,它对我有用。所以我认为这应该是一个SQL配置问题,例如权限或端口问题。您需要使用sqlserver客户端测试连接状态,并检查相关的连接问题。