简体   繁体   中英

Method open of object _connection failed

I am trying to connect to an SQL ce database within Excel. It keeps giving me the:

Method Open of object _connection failed

Error message whenever it gets to Conn.Open .

I've never used ADO before so I'm not sure what's going wrong.

Below is my connection script.

Sub SQLCeConnect()
Dim Conn As New ADODB.Connection
Dim Query As New ADODB.Command
Dim ConnStr As String
Dim RecordSet As New ADODB.RecordSet
Dim i As Integer

'the connection string
ConnStr = "Provider=Microsoft.SQLSERVER.CE.OLEDB.3.5;Data Source=X:\ADOTEST\MYDB.sdf;"

'Open ADO Connection
Conn.ConnectionString = ConnStr
Conn.Open
Query.ActiveConnection = Conn
Query.CommandText = "SELECT * From DoorLayers"

Set RecordSet = Query.Execute
RecordSet.Close
Conn.Close
Conn.ConnectionString = ""

Do While Not RecordSet.EOF
    For i = 0 To RecordSet.Fields.Count - 1
        Debug.Print RecordSet.Fields(i).Name, RecordSet.Fields(i).Value
    Next
    RecordSet.MoveNext
Loop
RecordSet.Close

End Sub

The is usually a bad connection string, but yours looks fine. The next most common cause is that you don't have the OLEDB provider drivers on your desktop. You can download it here

http://www.microsoft.com/en-us/download/details.aspx?id=5821

Are you closing the connection before use it on WHILE . You must close it after use the while instruction.

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