Connecting to sqlserver2012 localDB from VBA

Connecting to sqlserver2012 localDB from VBA

I have been having a very frustrating time trying to connect to a localDB database from Excel VBA.


I have created a database using Visual Studio 2012 Express and in the IDE the database seems fine. I can create data and query it without problem.

In Visual Studio the Connection Properties windows shows:

Name:                     D:\FISKDEV_EXCEL\FISKDBSOLN\FISKDBSOLN\FISKDB.MDF

Connection String:    Data Source=(LocalDB)\v11.0;AttachDbFilename=D:\FiskDev_Excel\FiskDBSoln\FiskDBSoln\FiskDB.mdf;Integrated Security=True

Provider:                 .NET Framework Data Provider for SQL Server

Primary File Path:     D:\FiskDev_Excel\FiskDBSoln\FiskDBSoln\FiskDB.mdf


I then try to connect to the automatic instance with the following code:


 Dim connStr As String
    Dim conn As ADODB.Connection
   
    connStr = "Server=(localDB)\v11.0;AttachDBFilename=D:\FiskDev_Excel\FiskDBSoln\FiskDBSoln\FiskDB.mdf;Integrated Security=True"
   
    Set conn = New ADODB.Connection
    conn.ConnectionString = connStr
    conn.OpenHowever the Open fails with the following message:

"Run-time Error  '-2147217887(80040e21)'

Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done."

Any pointer to what I am doing wrong would be greatfully received.
I've finally stumbled across a provider / connection string couple that allows connection to a LocalDB instance from a VBA program. The following code works.


     Dim conn As ADODB.Connection
     Dim rs As ADODB.Recordset
     Dim sqlStr As String

     connStr = "Driver={SQL Server native Client 11.0};Server=(LocalDB)\v11.0;AttachDBFileName=c:\ExcelTrial\tsetDB.mdf;Database=tsetDB;Trusted_Connection=Yes"
     sqlStr = "Select * from Customers"

     Set conn = New ADODB.Connection
     conn.ConnectionString = connStr
     conn.Open

     Set rs = conn.Execute(sqlStr)

     Do While Not rs.EOF
        Debug.Print rs!CompanyName
        rs.MoveNext
     Loop

     rs.Close
     Set rs = Nothing

Copyright © 2007-2012 www.chuibin.com Chuibin Copyright