Compile error user defined type not defined как исправить
Перейти к содержимому

Compile error user defined type not defined как исправить

Пользовательский тип не определен

Вы можете создать свои собственные типы данных в Visual Basic, однако они должны быть сначала определены в операторе Type. End Type или в свойстве зарегистрированной библиотеки объектов или библиотеки типов. Эта ошибка имеет следующие причины и способы решения:

Вы пытались объявить переменную или аргумент с неопределенным типом данных или определили неизвестный класс или объект.

Используйте оператор Type в модуле, чтобы определить новый тип данных. Если вы пытаетесь создать ссылку на класс, это класс должен быть видимым для проекта. Если вы ссылаетесь на класс в своей программе, то должны иметь модуль классов указанного имени в своем проекте. Проверьте правильность написания типа имени или имени объекта.

Тип, который вы хотите объявить находится в другом модуле, но он был объявлен как Private. Переместите определение типа в стандартный модуль, где он может быть объявлен как Public.

Данный тип является недопустимым, однако библиотека объектов или библиотека типов, в которой он определен, не зарегистрирована в Visual Basic. Отобразите диалоговое окно Ссылки, а затем выберите соответствующую библиотеку объектов или библиотеку типов. Например, если вы не установите флажок Объекты доступа к данным в диалоговом окне Ссылки, такие типы, как Database, Recordset и TableDef, не будут распознаваться и ссылки на них в коде будут вызывать эту ошибку.

Для получения дополнительной информации выберите необходимый элемент и нажмите клавишу F1 (для Windows) или HELP (для Macintosh).

См. также

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

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.

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

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.

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.

Open Notes

Получние данных для Excel с помощью запроса к базе данных

Если, например, требуется получить одно единственное значение с помощью запроса к базе данных (сам запрос может иметь заранее заданную конструкцию, меняющуюся в зависимости от определённых условий), то пригодится следующией код.

Для MS SQL

Sub Get_MSSQL_Data() Dim db As ADODB.Connection Dim rs As ADODB.Recordset Dim sqlStr As String Set rs = CreateObject("ADODB.Recordset") Set db = New ADODB.Connection db.Open _ "DRIVER=;SERVER=SName;UID=UserName;PWD=Password;DATABASE=DBName" sqlStr = "SELECT Count(*) as cnt FROM [DBName].[DB].[Table]" rs.Open sqlStr, db While Not rs.EOF str1 = rs.Fields("cnt").Value rs.MoveNext Wend rs.Close db.Close End Sub

Для других баз данных нужно изменить строку подключения:

Teradata ODBC Driver

на следующий вариант для Teradata:

OLE DB Provider for Oracle

на следующий вариант для Oracle:

User-defined type not defined

Для того, чтобы при выполнении кода не возникало ошибки «Compile error: User-defined type not defined»:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *