Ошибка access user defined type not defined

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

Jean-François Corbett's user avatar

asked Mar 18, 2011 at 8:27

Parth Bhatt's user avatar

Parth BhattParth Bhatt

19.4k28 gold badges133 silver badges216 bronze badges

1

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

learnAsWeGo's user avatar

learnAsWeGo

2,2522 gold badges13 silver badges19 bronze badges

answered Mar 18, 2011 at 8:43

Parth Bhatt's user avatar

Parth BhattParth Bhatt

19.4k28 gold badges133 silver badges216 bronze badges

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.

answered Mar 19, 2011 at 11:45

Jean-François Corbett's user avatar

2

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.

Set cn = CreateObject("ADODB.Connection")

ZygD's user avatar

ZygD

21.6k39 gold badges74 silver badges101 bronze badges

answered Sep 26, 2015 at 2:12

Aradhana Mohanty's user avatar

1

  • Remove From My Forums
  • Question

  • Hello all I’m trying to do a mail merge into Word. When I click on the button I’m getting the a Compile Error

    Please see the code below.

    Private Sub MailMergeButton_Click()
    On Error GoTo Err_MailMergeButton_Click
        Dim objwordApp As Word.Application
        Dim objWordDoc As Word.Document

       
        If AddressAlocationType = 3 Then Exit Sub

       
        Set objwordApp = CreateObject(«objword.application»)
        wordApp.Visible = True
        Select Case [AddressAlocationType]
        Case 1
            Set objWordDoc = wordApp.Documents.Add(«c:databaseW_L_G.dot»)
        Case 2
            Set objWordDoc = wordApp.Documents.Add(«c:databaseW_L_P.dot»)
        Case 3
            Exit Sub
        End Select

       
    Exit_MailMergeButton_Click:
        Exit Sub

    Err_MailMergeButton_Click:
        MsgBox Err.Description
        Resume Exit_MailMergeButton_Click

       
    End Sub

    Can someone be so kind to let me know what I’m doing wrong…

    Many thanks

Answers

  • You need to go in VBE windows, then menu Tools > References > then search for Microsoft Word xx.0 Object Library

    The xx is a Number, which can vary depending on which version of Office you have installed.

    To make use of the Word Object Library, you must have installed Word on your PC, I assume you have.

    You might use Late binding, to avoid using Word Object Library, but thats another topic.


    Daniel van den Berg | Washington, USA | «Anticipate the difficult by managing the easy»

    • Marked as answer by

      Thursday, November 10, 2011 3:26 PM

Астронавт

0 / 0 / 0

Регистрация: 02.12.2013

Сообщений: 19

1

17.03.2014, 15:04. Показов 29751. Ответов 9

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Уважаемые, помогите, запарился…
Есть макрос в Access, нужно вызывать этот макрос из excel (нужно именно так)
Ниже код:

Visual Basic
1
2
3
4
5
Sub m1()
Dim As cnn As ADODB.Connection
Set cnn = OpenDatabase("bd.accdb")
DoCmd.RunSavedImportExport "Import"
End sub

Показывает ошибку «User-defined type not defined», красит первую строчку в желтый цвет, выделяет вторую

Подключил следующие библиотеки:
Microsoft Access 14.0 Object Library
Microsoft Office 14.0 Access database engine Object Library
Microsoft Office 14.0 Object Library
Microsoft ADO Ext. 6.0 for DLL and Security
(Мб даже какие то из них лишние)

Я новичок в программировании, помогите пожалуйста, наверняка фигни понаписал



0



Апострофф

Заблокирован

17.03.2014, 15:10

2

Цитата
Сообщение от Астронавт
Посмотреть сообщение

Dim As cnn As ADODB.Connection

As — ключевое слово, напрягите фантазию, придумайте что-нибудь свое

Добавлено через 1 минуту
Пардон, просто удалите лишний As



2



Астронавт

0 / 0 / 0

Регистрация: 02.12.2013

Сообщений: 19

17.03.2014, 15:50

 [ТС]

3

As перед cnn появился после того, как вы оформили код как vb. У меня в коде его нет и не было.
Аномалия, но суть не в этом, вопрос остается в силе
Код:

Visual Basic
1
2
3
4
5
Sub m1()
Dim cnn As ADODB.Connection
Set cnn = OpenDatabase("bd.accdb")
DoCmd.RunSavedImportExport "Import"
End sub

Ошибка та же



0



2785 / 717 / 106

Регистрация: 04.02.2011

Сообщений: 1,443

17.03.2014, 16:43

4

Все вышеперечисленные библиотеки отключите, для ADODB подключите только «Microsoft ActiveX Data Objects X.X Library», где X.X я обозначил номер версии (зависит от того, что установлено у Вас в системе). Например у меня самая старшая доступная версия ADODB: Microsoft ActiveX Data Objects 6.1 Library. Кстати, последнюю версию не всегда обязательно подключать, сойдет и 2.8.



1



Астронавт

0 / 0 / 0

Регистрация: 02.12.2013

Сообщений: 19

17.03.2014, 17:05

 [ТС]

5

Спасибо! Данная ошибка решена
Теперь заругался на OpenDatabase…
Переписать код:

Visual Basic
1
2
3
4
5
6
Sub m1()
Dim cnn As ADODB.Connection
Set cnn = New Access.Application
cnn.OpenCurrentDatabase "bd.accdb"
DoCmd.RunSavedImportExport "Import"
End Sub

Теперь выдает ошибку «type mismatch»..
Не подскажете, в чем причина?
Вообще суть такая — открывается существующая база, выполняется импорт по отработанной схеме, база закрывается. Ну потом еще хотел вписать «тихий режим».. Но сейчас не об этом



0



2785 / 717 / 106

Регистрация: 04.02.2011

Сообщений: 1,443

17.03.2014, 19:00

6

Лучший ответ Сообщение было отмечено Астронавт как решение

Решение

Не-не-не. Вы объявлять должны ADODB, чтобы использовать язык SQL для доступа к БД. Если вам нужны объекты Access, его объектная модель, так и подключайте Access.
Microsoft Access XX.X Library (Microsoft Access XX.X Library lkz Office 2010).



1



mobile

Эксперт MS Access

26784 / 14463 / 3192

Регистрация: 28.04.2012

Сообщений: 15,782

18.03.2014, 02:21

7

Лучший ответ Сообщение было отмечено Астронавт как решение

Решение

Астронавт, Вам нужно использовать DAO для доступа к объектам БД. Чтобы вызвать макрос Access из Excel, можно использовать такой код

Visual Basic
1
2
3
4
5
6
Sub m1()
Dim app As Object
Set app = CreateObject("Access.Application")
app.opencurrentdatabase "C:путьbd.accdb", False
app.DoCmd.RunSavedImportExport "Import"
End Sub



1



0 / 0 / 0

Регистрация: 02.12.2013

Сообщений: 19

18.03.2014, 09:37

 [ТС]

8

mc-black, спасибо за разъяснения! Буду разбираться с этим!
mobile, большое спасибо! Все отлично работает!
Только объясните пожалуйста, за что отвечает False в четвертой строчке?



0



Эксперт MS Access

26784 / 14463 / 3192

Регистрация: 28.04.2012

Сообщений: 15,782

18.03.2014, 10:40

9

Второй параметр OpenCurrentDatabase это необязательный аргумент типа Boolean. Логическое значение, указывающее, следует ли открыть базу данных в режиме монопольного доступа. По умолчанию, присваивается значение False, и база данных открывается в режиме общего доступа. В принципе, можно не писать False. Но по привычке :-)



1



0 / 0 / 0

Регистрация: 02.12.2013

Сообщений: 19

19.03.2014, 16:47

 [ТС]

10

mobile, еще вопросик
Ваш код работает без открытия базы
То есть запуская макрос из excel база access не запускается (или я чего-то не понял)
Если так, то допустим у меня в коде открывается файл excel (при помощи workbooks.open filename:=…)
Потом открывшийся файл начинает обрабатываться: удаляются строки, добавляются формулы, меняются форматы ячеек, создаются и удаляются листы, сводные таблицы, и так далее (в коде присутствуют такие вещи как «select», «selection», «activate», «activesheet»…). Смогу ли я при таком коде обрабатывать документ так же без открытия?
То есть если книга не открыта, то поймет ли обработчик такие понятия как «активный лист» и подобные?



0



Compile error: User-defined type not defined

Are you sitting there staring at this error on your VBA screen and getting frustrated? No worries, we shall fix it.

But before deep diving into the root cause and solution to fix this error, let’s understand the correct procedure for using an object in our code. It will ease the debugging process.

For this example, let’s look at a Dictionary object.

DICTIONARY in VBA:

A DICTIONARY is an object similar to the VBA COLLECTION object with the following differences:

  1. The values of the keys can be updated or changed later and
  2. The key / item value can easily be checked for existence without completely iterating through all the items. This also helps to retrieve values easily.

If you’re a beginner, just imagine that this object is a real time dictionary where the keys are the words and items are the respective definitions. As in a dictionary, in the VBA object we do not need to iterate through all the keys to find the value of one specific key. 

And just like any other object in VBA, we can use a dictionary object by adding the corresponding reference through Tools menu. Declaration and definition of objects can be done through early or late binding methods per the developer’s convenience.

Resolving the Error

The error in the title is a compile time error that is encountered when you compile the code.

Analyze the meaning and “ROOT CAUSE” of the error:

Let us split and read the error to understand it better.

User-defined type | not defined

First, let’s try to understand we have encountered the error because something is

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.

Refer to the sample code below to understand the difference between early and late binding.

Late binding:

' Create a dictionary object using the late binding method.
    Dim obdict As Object
    Set obdict = CreateObject("Scripting.Dictionary")

Early binding:

' Create a dictionary object using the early binding method.
    Dim obdict As New Scripting.Dictionary

Solution:

Try one of the following steps to resolve the error:

Method 1

Maybe VBA doesn’t understand that you have defined the object. In VBA, you need to add the respective reference for the object to let the language know that you have properly defined it.

  1. Goto the menu Tools-> References
  2. Select the library “Microsoft Scripting Runtime.” (This varies depending on the object used. Here the same dictionary object is considered for explanation purposes
  3. Click on the “OK” button and close the dialog
  4. Now you can compile the code and see that the error doesn’t appear anymore

References list with Microsoft Scripting Runtime selected

Note: All this is NOT mandatory if you are following “late binding” method.

Method 2

Use the late binding method where you declare a generic object first, then define its type. This does not require any reference.

Syntax:

Dim <variable> As Object

Set <variable> = CreateObject("Scripting.Dictionary")

Example for an Excel sheet object:

Dim ExcelSheet As Object

Set ExcelSheet = CreateObject("Excel.Sheet")

Example for a dictionary object:

'Example of creating a dictionary object

Dim odict As Object

Set odict = CreateObject("Scripting.Dictionary")

Video Example

The video below shows how to resolve the error using each of the two methods above.

title keywords f1_keywords ms.prod ms.assetid ms.date ms.localizationpriority

User-defined type not defined (VBA)

vblr6.chm1011292

vblr6.chm1011292

office

60e0da5e-c498-7a2f-46c6-c09d59fc607a

12/27/2018

high

User-defined type not defined

You can create your own data types in Visual Basic, but they must be defined first in a Type…End Type statement or in a properly registered object library or type library. 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. If you are trying to create a reference to a class, the class must be visible to the project. If you are referring to a class in your program, you must have a class module of the specified name in your project. Check the spelling of the type name or name of the object.

  • The type you want to declare is in another module but has been declared Private. Move the definition of the type to a standard module where it can be Public.

  • The type is a valid type, but the object library or type library in which it is defined isn’t registered in Visual Basic. Display the References dialog box, and then select the appropriate object library or type library. For example, if you don’t check the Data Access Object in the References dialog box, types like Database, Recordset, and TableDef aren’t recognized and references to them in code cause this error.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

See also

  • Visual Basic how-to topics

[!includeSupport and feedback]

  • Ошибка abs приора 16 клапанов
  • Ошибка access to requested operation is denied перевод
  • Ошибка abs плавают обороты
  • Ошибка access denied origin
  • Ошибка abs пежо партнер типи