Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiler Error: User-defined types not defined

Tags:

excel

vba

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 
like image 278
Parth Bhatt Avatar asked Mar 18 '11 08:03

Parth Bhatt


People also ask

What does compile error user defined type not defined mean?

“not defined”. A possible reason for the error to occur is that you are utilizing the early binding method to declare and define the object, but the required reference has not been added.

What does user defined type not defined mean?

This error has the following causes and solutions: You tried to declare a variable or argument with an undefined data type or you specified an unknown class or object. Use the Type statement in a module to define a new data type.

How do I fix compile error sub or function not defined?

To correct this errorMake sure that the procedure name is spelled correctly. Find the name of the project containing the procedure you want to call in the References dialog box. If it does not appear, click the Browse button to search for it. Select the check box to the left of the project name, and then click OK.


2 Answers

I had forgotten to add a reference to "Microsoft ActiveX Data Objects 2.5 Library": This reference is required for early binding.

How to get to that reference:

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

Other libraries that work include:

Microsoft ActiveX Data Objects 2.6 Library

Microsoft ActiveX Data Objects 2.7 Library

Microsoft ActiveX Data Objects 2.8 Library

Microsoft ActiveX Data Objects 6.1 Library

like image 198
Parth Bhatt Avatar answered Oct 20 '22 21:10

Parth Bhatt


You can use late binding:

Dim cn As Object 

will make the problem go away. VBA will make the reference automatically when the Set cn = CreateObject("ADODB.Connection") statement is executed.

like image 33
Jean-François Corbett Avatar answered Oct 20 '22 19:10

Jean-François Corbett