简体   繁体   中英

Excel VBA user defined type not defined-

I'm trying to create an excel program that can get data from sheet1 to sheet2 within the same file using VBA. But when I declared the ADODB, it does not appear in the drop down list. And when I try to run sub I get the 'user defined type not defined' error. Can anyone please share with me any fixes?

The code is as below:

Sub testsql()

'declare variable
Dim objMyConn As ADODB.Connection
Dim objMyCmd As ADODB.Command
Dim objMyRecordSet As ADODB.Recordset

Set objMyConn = New ADODB.Connection
Set objMyCmd = New ADODB.Command
Set objMyRecordSet = New ADODB.Recordset

'open connection
objMyConn.connectionstring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & wbWorkBook & ";Extended Properties=Excel 8.0;"
objMyConn.Open

'set and execute command
Set objMyCmd.activeconnection = objMyConn
objMyCmd.CommandText = "select top 10000 [Die No], Description from DieMaintenanceEntry"
objMyCmd.CommandType = adcmdtext


'open recordset
Set objMyRecordSet.Source = objMyCmd
objMyRecordSet.Open

'copy data to excel
ActiveWorkbook.Sheets("Display-Die Maintenance Summary").ActiveSheet.Range("A5").CopyFromRecordset (objMyRecordSet)

End Sub

You can solve this in two ways:

  1. Early Binding (as hinted by your code)
    What you need to do is reference the correct Microsoft ActiveX Data Object . For my version, it is 6.1 .

    参考图书馆

  2. Using Late Binding (No need to reference library)

     Dim objMyConn As Object '/* Declare object type variable */ Dim objMyCmd As Object Dim objMyRecordset As Object '/* Set using create object */ Set objMyConn = CreateObject("ADODB.Connection") Set objMyCmd = CreateObject("ADODB.Command") Set objMyRecordset = CreateObject("ADODB.Recordset") 

As for which to use, I can only give suggestion. During development, use Early Binding for you to take advantage of Intellisense . At deployment, change to Late Binding to overcome version compatibility issues.

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