Access ошибка user defined type not defined

This repo is no longer accepting new issues. To request changes, you can create a branch, make changes, then submit a PR. For more resources, see README.MD - VBA-Docs/user-defined-type-not-defined....

Permalink

Cannot retrieve contributors at this time

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

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]

Good Afternoon (at least here it is afternoon),

I have this code block I’ve been using for years without issue. Today I copied it to another application to incorporate its use there. I am getting a compile error on this line     fDialog As FileDialog

The block in its entirety is;

Private Sub doc2docx_Click()
    Dim strFilename As String
    Dim strDocName As String
    Dim strPath As String
    Dim oApp As Object
    Dim oDoc As Object
    Dim fDialog As FileDialog
    Dim intPos As Integer
    Dim strPassword As String
    Dim strWritePassword As String
    Set fDialog = Application.FileDialog(4) ' msoFileDialogFolderPicker
    With fDialog
        .Title = "Select folder and click OK"
        .AllowMultiSelect = False
        .InitialView = msoFileDialogViewList
        If .Show <> -1 Then
            MsgBox "Conversion Cancelled By User", , "List Folder Contents"
            Exit Sub
        End If
        strPath = fDialog.SelectedItems.Item(1)
        If Right(strPath, 1) <> "" Then strPath = strPath + ""
    End With
    Set oApp = CreateObject(Class:="Word.Application")
    If oApp.Documents.Count > 0 Then
        oApp.Documents.Close SaveChanges:=-2 ' wdPromptToSaveChanges
    End If
    If Left(strPath, 1) = Chr(34) Then
        strPath = Mid(strPath, 2, Len(strPath) - 2)
    End If
    strFilename = Dir(strPath & "*.doc")
    strPassword = InputBox("Enter password to open the document")
    strWritePassword = InputBox("Enter password to edit the document")
    Do While strFilename <> ""
        Set oDoc = oApp.Documents.Open(FileName:=strPath & strFilename, _
                                  PasswordDocument:=strPassword, _
                                  WritePasswordDocument:=strWritePassword, _
                                  AddToRecentFiles:=False)
        strDocName = oDoc.FullName
        intPos = InStrRev(strDocName, ".")
        strDocName = Left(strDocName, intPos - 1)
        strDocName = strDocName & ".docx"
        oDoc.SaveAs2 FileName:=strDocName, _
                     FileFormat:=12, _
                     CompatibilityMode:=14
        oDoc.Close SaveChanges:=0 ' wdDoNotSaveChanges
        strFilename = Dir
    Loop
    oApp.Quit
End Sub

My references are in this order;

Visual Basic For Application

Microsoft Access 16.0 Object Library

OLE Animation

Microsoft Office 16.0 Access Database Engine Object Library

Microsoft ActiveX Data Objects 6.0 Library

Microsoft Ward 16.0 Object Library

Thank you for your assistance with his issue.


Just takes a click to give thanks for a helpful post or answer.
Please vote “Helpful” or Mark as “Answer” as appropriate.
Chris Ward
Microsoft Community Contributor 2012

I’m receiving a compile error on the following line of code:

Dim oXL As Excel.Application

The code is in VB in MS Access 2007. The line above is the beginning of a segment to generate an MS Excel file. The obvious answer to me was to ensure that the «Microsoft Office 12.0 Object Library» is checked under Tools > References. I’ve done this but the error persists. Does Excel need to be installed side-by-side for this to work? What have I done wrong? Thanks in advance.

Tim Williams's user avatar

Tim Williams

147k8 gold badges94 silver badges120 bronze badges

asked Jul 19, 2012 at 21:10

Gedalya's user avatar

1

You need to reference Microsoft Excel 12.0 Object Library or use late binding. Late binding is almost always necessary if you will be sharing your project with users who may have different versions of Excel installed.

For late binding, you would instead do:

Dim oXL as object
Set oXL = CreateObject("Excel.Application")

Then your code should work as expected, without the need to make the reference… assuming you aren’t using any other Excel specific values or objects.

answered Jul 19, 2012 at 21:16

Daniel's user avatar

DanielDaniel

12.9k2 gold badges35 silver badges60 bronze badges

2

Содержание

  1. User-defined type not defined
  2. See also
  3. Support and feedback
  4. PRB: ADO: Compile Error: User-Defined Type Not Defined
  5. Symptoms
  6. Cause
  7. Resolution
  8. Status
  9. More Information
  10. Steps to Reproduce Behavior

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

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

PRB: ADO: Compile Error: User-Defined Type Not Defined

Symptoms

When you compile your ADO project, you receive the following error:

Compile error: User-defined type not defined

This can occur on either a Connection or Command object.

Cause

You may have referenced one of the following libraries instead of the Microsoft ActiveX Data Objects (ADODB) type library:

Microsoft ActiveX Data Objects Recordset (ADOR) type library.

Microsoft ActiveX Data Objects (Multi-dimensional) (ADOMD) type library.

Resolution

Remove the incorrect type library reference from your project, and add a reference to the correct type library.

Status

This behavior is by design.

More Information

Steps to Reproduce Behavior

Create a new project and add a command button (Command1) to a form.

Add a reference to the Microsoft ActiveX Data Objects Recordset Library.

Add the following code to the form:

Run the project and click the command button. The error appears.

Remove the reference, and add a reference to the Microsoft ActiveX Data Objects Library.

Click the command button. The error does not appear.

Microsoft Access users will have to use ADODB.Connection to avoid confusion with the DAO Connection object.

If the Intellitype feature is turned on, you should notice that it does not show Connection as a valid object with the ADOR type library, but does with the ADODB type library. This is a good indication that you do not have the correct type library referenced.

This error can also occur when referencing objects in other type libraries that aren’t referenced.

Источник

Астронавт

0 / 0 / 0

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

Сообщений: 19

1

17.03.2014, 15:04. Показов 28946. Ответов 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



2783 / 715 / 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



2783 / 715 / 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

26772 / 14451 / 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

26772 / 14451 / 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



Понравилась статья? Поделить с друзьями:

Читайте также:

  • Accu chek e 1 код ошибки
  • Accu chek active ошибка еее что делать
  • Access номер ошибки 2102
  • Accu chek active ошибка eee как устранить
  • Accu chek active ошибка e 5 что значит

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии