关于vba:编译器错误:未定义用户定义的类型

Compiler Error: User-defined types not defined

我在此行上收到编译时错误"未定义用户定义类型":

1
Dim cn As ADODB.Connection

怎么了?

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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


我忘记添加对" Microsoft ActiveX数据对象2.5库"的引用:early binding需要此引用。

How to get to that reference:

工具>参考>选中" Microsoft ActiveX数据对象2.5库"前面的复选框。

Other libraries that work include:

Microsoft ActiveX数据对象2.6库

Microsoft ActiveX数据对象2.7库

Microsoft ActiveX数据对象2.8库

Microsoft ActiveX数据对象6.1库


您可以使用后期绑定:

1
Dim cn As Object

将使问题消失。当执行Set cn = CreateObject("ADODB.Connection")语句时,VBA将自动进行引用。


我尝试添加Microsoft ActiveX数据对象2.5和2.8库,但是没有成功。但是当我尝试创建如下所示的新对象时,它起作用了。

1
Set cn = CreateObject("ADODB.Connection")