简体   繁体   中英

VBA connecting to local SQL Server

I have SQL Server 2008 installed on my PC and I'm writing VBA code to populate a table on that database. I was able to stitch together the below code from various online sources:

Sub connect()
Dim conn As ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim strConn As String
Dim strSRV As String
Dim strDB As String
Dim sql_login As String
Dim sql_pass As String

    'Create the connection string
    strSRV = ".\SQLEXPRESS"
    strDB = "backend"
    sql_login = "asd"
    sql_pass = "asd"

    strConn = "Provider=SQLNCLI10" & _
              "Server=" & strSRV & ";" & _
              "Database=" & strDB & ";" & _
              "Uid=" & sql_login & ";" & _
              "Pwd=" & sql_pass & ";"


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

    ' Open the connection and execute
    conn.Open strConn
    Set rs = conn.Execute("SELECT * FROM *;")

    'Check we have data
    If Not rs.EOF Then
        'Transfer result
        Sheets(1).Range("A1").CopyFromRecordset rs

    'Close Recordset
    rs.Close

    Else
        MsgBox "Error: No records returned.", vbCritical
    End If

    'Clean up
    If CBool(conn.State And adStateopen) Then conn.Close
    Set conn = Nothing
    Set rs = Nothing
End Sub

Currently I'm getting an error:

Provider cannot be found

From online research I found that it can be due to ODBC config, so I went to ODBC Data Source Admin. There were 3 User Data Sources defined: dBASE Files, Excel Files and MS Access Database. I added a third one for SQL Server Native Client 10.0.

I was not able to find the answer at connectionstrings.com which seems to be a popular reference. What's the reason I'm getting the error? and how can I fix it in general? At one point my VBA will point to a remote server, so I don't want the solution to be a local workaround.

Looks like your strConn is missing a semicolon...try this and see if anything is different:-

 strConn = "Provider=SQLNCLI10;" & _
              "Server=" & strSRV & ";" & _
              "Database=" & strDB & ";" & _
              "Uid=" & sql_login & ";" & _
              "Pwd=" & sql_pass & ";"

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