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

I’m getting the above error when trying to execute this macros. I’m pretty new to Macros and coding in general so please forgive the ignorance.

Sub DeleteEmptyRows()

Dim oTable As Table, oRow As Row, _
TextInRow As Boolean, i As Long

Application.ScreenUpdating = False

For Each oTable In ActiveDocument.Tables
    For Each oRow In oTable.Rows

        TextInRow = False

        For i = 2 To oRow.Cells.Count
            If Len(oRow.Cells(i).Range.Text) > 2 Then
                'end of cell marker is actually 2 characters
                TextInRow = True
                Exit For
            End If
        Next

        If TextInRow = False Then
            oRow.Delete
        End If
    Next
Next
Application.ScreenUpdating = True

End Sub

Adrian Mole's user avatar

Adrian Mole

50.1k163 gold badges51 silver badges83 bronze badges

asked Jun 17, 2014 at 10:34

holdo1's user avatar

3

Your error is caused by these:

Dim oTable As Table, oRow As Row,

These types, Table and Row are not variable types native to Excel. You can resolve this in one of two ways:

  1. Include a reference to the Microsoft Word object model. Do this from Tools | References, then add reference to MS Word. While not strictly necessary, you may like to fully qualify the objects like Dim oTable as Word.Table, oRow as Word.Row. This is called early-binding. enter image description here
  2. Alternatively, to use late-binding method, you must declare the objects as generic Object type: Dim oTable as Object, oRow as Object. With this method, you do not need to add the reference to Word, but you also lose the intellisense assistance in the VBE.

I have not tested your code but I suspect ActiveDocument won’t work in Excel with method #2, unless you properly scope it to an instance of a Word.Application object. I don’t see that anywhere in the code you have provided. An example would be like:

Sub DeleteEmptyRows()
Dim wdApp as Object
Dim oTable As Object, As Object, _
TextInRow As Boolean, i As Long

Set wdApp = GetObject(,"Word.Application")

Application.ScreenUpdating = False

For Each oTable In wdApp.ActiveDocument.Tables

answered Jun 17, 2014 at 12:09

David Zemens's user avatar

David ZemensDavid Zemens

53k11 gold badges81 silver badges130 bronze badges

0

I am late for the party. Try replacing as below, mine worked perfectly-
«DOMDocument» to «MSXML2.DOMDocument60»
«XMLHTTP» to «MSXML2.XMLHTTP60»

answered May 2, 2019 at 15:38

GideonMetre's user avatar

Sub DeleteEmptyRows()  

    Worksheets("YourSheetName").Activate
    On Error Resume Next
    Columns("A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete

End Sub

The following code will delete all rows on a sheet(YourSheetName) where the content of Column A is blank.

EDIT: User Defined Type Not Defined is caused by «oTable As Table» and «oRow As Row». Replace Table and Row with Object to resolve the error and make it compile.

answered Jun 17, 2014 at 10:51

Olle89's user avatar

Olle89Olle89

6687 silver badges22 bronze badges

1

I’m getting the above error when trying to execute this macros. I’m pretty new to Macros and coding in general so please forgive the ignorance.

Sub DeleteEmptyRows()

Dim oTable As Table, oRow As Row, _
TextInRow As Boolean, i As Long

Application.ScreenUpdating = False

For Each oTable In ActiveDocument.Tables
    For Each oRow In oTable.Rows

        TextInRow = False

        For i = 2 To oRow.Cells.Count
            If Len(oRow.Cells(i).Range.Text) > 2 Then
                'end of cell marker is actually 2 characters
                TextInRow = True
                Exit For
            End If
        Next

        If TextInRow = False Then
            oRow.Delete
        End If
    Next
Next
Application.ScreenUpdating = True

End Sub

Adrian Mole's user avatar

Adrian Mole

50.1k163 gold badges51 silver badges83 bronze badges

asked Jun 17, 2014 at 10:34

holdo1's user avatar

3

Your error is caused by these:

Dim oTable As Table, oRow As Row,

These types, Table and Row are not variable types native to Excel. You can resolve this in one of two ways:

  1. Include a reference to the Microsoft Word object model. Do this from Tools | References, then add reference to MS Word. While not strictly necessary, you may like to fully qualify the objects like Dim oTable as Word.Table, oRow as Word.Row. This is called early-binding. enter image description here
  2. Alternatively, to use late-binding method, you must declare the objects as generic Object type: Dim oTable as Object, oRow as Object. With this method, you do not need to add the reference to Word, but you also lose the intellisense assistance in the VBE.

I have not tested your code but I suspect ActiveDocument won’t work in Excel with method #2, unless you properly scope it to an instance of a Word.Application object. I don’t see that anywhere in the code you have provided. An example would be like:

Sub DeleteEmptyRows()
Dim wdApp as Object
Dim oTable As Object, As Object, _
TextInRow As Boolean, i As Long

Set wdApp = GetObject(,"Word.Application")

Application.ScreenUpdating = False

For Each oTable In wdApp.ActiveDocument.Tables

answered Jun 17, 2014 at 12:09

David Zemens's user avatar

David ZemensDavid Zemens

53k11 gold badges81 silver badges130 bronze badges

0

I am late for the party. Try replacing as below, mine worked perfectly-
«DOMDocument» to «MSXML2.DOMDocument60»
«XMLHTTP» to «MSXML2.XMLHTTP60»

answered May 2, 2019 at 15:38

GideonMetre's user avatar

Sub DeleteEmptyRows()  

    Worksheets("YourSheetName").Activate
    On Error Resume Next
    Columns("A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete

End Sub

The following code will delete all rows on a sheet(YourSheetName) where the content of Column A is blank.

EDIT: User Defined Type Not Defined is caused by «oTable As Table» and «oRow As Row». Replace Table and Row with Object to resolve the error and make it compile.

answered Jun 17, 2014 at 10:51

Olle89's user avatar

Olle89Olle89

6687 silver badges22 bronze badges

1

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.

user-defined type not defined vba

cobra77777

Дата: Понедельник, 07.09.2015, 19:50 |
Сообщение № 1

Группа: Заблокированные

Ранг: Участник

Сообщений: 68


Репутация:

-14

±

Замечаний:
80% ±


Excel 2013

Здравствуйте! Юзаю 2013 офис (excel) при запуске макроса выходит ошибка: user-defined type not defined vba . Что делать ? Какую то библиотеку нужно установить (галочку) ?

 

Ответить

RAN

Дата: Понедельник, 07.09.2015, 19:53 |
Сообщение № 2

Группа: Друзья

Ранг: Экселист

Сообщений: 5660

определяемый пользователем тип не определен VBA
И чё?


Быть или не быть, вот в чем загвоздка!

 

Ответить

cobra77777

Дата: Понедельник, 07.09.2015, 19:55 |
Сообщение № 3

Группа: Заблокированные

Ранг: Участник

Сообщений: 68


Репутация:

-14

±

Замечаний:
80% ±


Excel 2013

хотел узнать как от этой ошибки избавиться ?

 

Ответить

Serge_007

Дата: Понедельник, 07.09.2015, 20:02 |
Сообщение № 4

Группа: Админы

Ранг: Местный житель

Сообщений: 16326


Репутация:

2723

±

Замечаний:
±


Excel 2016

при запуске макроса выходит ошибка

Какого макроса?


ЮMoney:41001419691823 | WMR:126292472390

 

Ответить

cobra77777

Дата: Понедельник, 07.09.2015, 20:09 |
Сообщение № 5

Группа: Заблокированные

Ранг: Участник

Сообщений: 68


Репутация:

-14

±

Замечаний:
80% ±


Excel 2013

привожу маленкий кусок кода, почему то при объявлении и запуске макроса :

[vba]

Код

Dim myFile, curPath As String
Dim MyDoc As Document < ————————————выходит эта ошибка user-defined type not defined
Dim rownum, colnum, rownum_all, i, j, k As Long
Dim b As Boolean
Dim snils, temp As Variant

[/vba]

Сообщение отредактировал Serge_007Понедельник, 07.09.2015, 20:15

 

Ответить

Serge_007

Дата: Понедельник, 07.09.2015, 20:17 |
Сообщение № 6

Группа: Админы

Ранг: Местный житель

Сообщений: 16326


Репутация:

2723

±

Замечаний:
±


Excel 2016

Конечно ошибка. Что за объявление As Document? Нет такого в VBA Excel


ЮMoney:41001419691823 | WMR:126292472390

 

Ответить

KSV

Дата: Понедельник, 07.09.2015, 20:19 |
Сообщение № 7

Группа: Друзья

Ранг: Ветеран

Сообщений: 770


Репутация:

255

±

Замечаний:
0% ±


Excel 2013

Подключите к своему проекту библиотеку Microsoft Word 15.0 Object Library в меню Tools -> References


KSV.VBA@gmail.com
Яндекс.Деньги: 410011921213333

 

Ответить

RAN

Дата: Понедельник, 07.09.2015, 21:02 |
Сообщение № 8

Группа: Друзья

Ранг: Экселист

Сообщений: 5660


Быть или не быть, вот в чем загвоздка!

 

Ответить

nataxa777

0 / 0 / 0

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

Сообщений: 26

1

07.06.2013, 14:12. Показов 44758. Ответов 3

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


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

user-defined type not defined — эта ошибка возникает тогда из Excel должен создаться документ отчета у Word, а при запуске на исполнение на первой строчке нижнего примера возникает ошибка.
Вот фрагмент (сам код большой и это пример из книжки). Помогите пожалуйста разобраться в чем ошибка и как ее устранить?

Visual Basic
1
2
3
Dim oWord As Word.Application
Set oWord = CreateObject("Word.Application")
oWord.Visible = True

Заранее благодарна!!!



0



Pavel55

994 / 353 / 135

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

Сообщений: 764

07.06.2013, 15:51

2

Visual Basic
1
2
Dim oWord As Object
Set oWord = CreateObject("Word.Application")



1



0 / 0 / 0

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

Сообщений: 26

07.06.2013, 16:09

 [ТС]

3

Pavel55, спасибо Вам огромное!!! все получилось



0



Hugo121

6919 / 2829 / 543

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

Сообщений: 8,644

18.02.2016, 22:15

4

Кстати, если уж исправлять ошибки книжек, то можно ещё и так:

Visual Basic
1
2
Dim oWord As New Word.Application
oWord.Visible = True

Но! Сперва подключите библиотеку Ворда в Tools->References!



0



Понравилась статья? Поделить с друзьями:
  • Vba обработчики ошибок
  • Vds basic provider ошибка 1
  • Vba ошибка out of stack space
  • Vba обработка ошибок try
  • Vdo 1324 ошибка 9053