vba 编译器错误:未定义用户定义的类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5349580/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Compiler Error: User-defined types not defined
提问by Parth Bhatt
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
回答by Parth Bhatt
I had forgotten to add a reference to "Microsoft ActiveX Data Objects 2.5 Library": This reference is required for early binding
.
我忘记添加对“Microsoft ActiveX Data Objects 2.5 Library”的引用:此引用是early binding
.
How to get to that reference:
如何获得该参考:
Tools > References > Check the checkbox in front of "Microsoft ActiveX Data Objects 2.5 Library"
工具 > 参考 > 选中“Microsoft ActiveX Data Objects 2.5 Library”前面的复选框
Other libraries that work include:
其他可用的库包括:
Microsoft ActiveX Data Objects 2.6 Library
Microsoft ActiveX 数据对象 2.6 库
Microsoft ActiveX Data Objects 2.7 Library
Microsoft ActiveX 数据对象 2.7 库
Microsoft ActiveX Data Objects 2.8 Library
Microsoft ActiveX 数据对象 2.8 库
Microsoft ActiveX Data Objects 6.1 Library
Microsoft ActiveX 数据对象 6.1 库
回答by Jean-Fran?ois Corbett
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.
将使问题消失。VBA 会在Set cn = CreateObject("ADODB.Connection")
语句执行时自动进行引用。
回答by Aradhana Mohanty
I tried adding Microsoft ActiveX Data Objects 2.5 and 2.8 library, but it did not work out. But when I tried creating new object like below it worked.
我尝试添加 Microsoft ActiveX Data Objects 2.5 和 2.8 库,但没有成功。但是当我尝试创建像下面这样的新对象时,它起作用了。
Set cn = CreateObject("ADODB.Connection")