Compiler Error: User-defined types not defined

calendar_today Asked Mar 18, 2011
thumb_up 19 upvotes
history Updated April 16, 2026

Question posted 2011 · +11 upvotes

I get the compile-time error “User-defined types not defined” on this line:

Dim cn As ADODB.Connection`

What could be wrong?

Code:

Sub test()

    Dim cn As ADODB.Connection

    'Not the best way to get the name, just convenient for notes

    strFile = Workbooks(1).FullName
    strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"
    Set cn = CreateObject("ADODB.Connection")
    'For this to work, you must create a DSN and use the name in place of

    'DSNName

    'strSQL = "INSERT INTO [ODBC;DSN=DSNName;].NameOfMySQLTable " & "Select AnyField As NameOfMySQLField FROM [Sheet1$];"
     strSQL = "SELECT F1 FROM [Sheet1$];"
     cn.Execute strSQL
End Sub

Accepted answer +19 upvotes

I had forgotten to add a reference to “Microsoft ActiveX Data Objects 2.5 Library”:

Tools > References > Check the checkbox in front of “Microsoft ActiveX Data Objects 2.5 Library”

Top excel-vba Q&A (6)

+19 upvotes ranks this answer #20 out of 136 excel-vba solutions on this site — top 15%.