Меню

Vba excel ошибка 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

47.9k138 gold badges48 silver badges78 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

52.7k11 gold badges79 silver badges129 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.

Contents

  • DICTIONARY in VBA:
  • Resolving the Error
      • Analyze the meaning and “ROOT CAUSE” of the error:
      • Solution:
        • Method 1
        • Method 2
    • Video Example

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.

DO_oK

11 / 11 / 7

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

Сообщений: 87

1

08.08.2017, 09:32. Показов 7767. Ответов 11

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


Привет! Поискал решение, не нашел, давно не обращался за помощью на форум так вот ругается на первую же строчку кода, т.е. на «Sub FSD()». Весь код:

PureBasic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
Sub FSD()
    FolderName = "O:путькпапке_кириллицей" 
 
    Dim coll As New Collection, filename
    filename = Dir(FolderPath$ & "*.htm")
    While filename <> ""
        coll.Add filename    ' ñ÷èòûâàåì â êîëåêöèþ coll íóæíûå èìåíà ôàéëîâ
        filename = Dir
    Wend
    Dim pos As Long
    Dim rowcunt As Long
    rowcunt = 3
    pcname = "<TR><TD><TD><TD>Êîìïüþòåð&nbsp;&nbsp;<TD>"
    
    For Each filename In coll
     Dim fso As New FileSystemObject
     Dim ts As TextStream
     Set ts = fso.OpenTextFile(FolderName & filename, ForReading)
     Dim TextLine As String
     Do Until ts.AtEndOfStream
         TL = ts.ReadLine
         pos = InStr(1, pcname, TL)
         If pos > 0 Then
            Range("B" & rowcunt).Value = Right(TL, Len(TL) - 42)
         End If
     Loop
     rowcunt = rowcunt + 1
     ts.Close
    Next
End Sub

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



es geht mir gut

11264 / 4746 / 1183

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

Сообщений: 11,437

08.08.2017, 09:42

2

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

FSD()

Обзови по другому FSD_1 , например.



0



11 / 11 / 7

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

Сообщений: 87

08.08.2017, 09:45

 [ТС]

3

Переименовал в FSD_1(), не работает. Вообще от имени не зависит пробовал разные варианты и кириллицу тоже



0



6874 / 2806 / 533

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

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

08.08.2017, 09:46

4

Библиотека с FileSystemObject подключена?



0



11 / 11 / 7

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

Сообщений: 87

08.08.2017, 09:50

 [ТС]

5

Если речь идет об этом то видимо нет. Можно поподробней?

Миниатюры

User-defined type not defined. Ругается на объявление корневой процедуры
 



0



6874 / 2806 / 533

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

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

08.08.2017, 10:17

6

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

Решение

Найдите и подключите Microsoft scripting runtime scrrun.dll



3



mobile

Эксперт MS Access

26771 / 14450 / 3192

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

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

08.08.2017, 10:24

7

Библиотека Microsoft Scripting Runtime. Но часто применяют позднее связывание без объявления в референсах: вместо Dim fso As New FileSystemObject пишут

Visual Basic
1
2
Dim fso As Object
Set fso = createobject("scripting.FileSystemObject")

Добавлено через 31 секунду
Аппаздал



4



11 / 11 / 7

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

Сообщений: 87

08.08.2017, 10:25

 [ТС]

8

Проблема решилась, спасибо!

Найдите и подключите Microsoft scripting runtime scrrun.dll



0



es geht mir gut

11264 / 4746 / 1183

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

Сообщений: 11,437

08.08.2017, 10:29

9

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

Аппаздал

Зато в этом случае ничего не надо подключать .



0



DO_oK

11 / 11 / 7

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

Сообщений: 87

09.08.2017, 07:37

 [ТС]

10

Попробовал так, остается ошибка, не подскажите в чем дело?

PureBasic
1
2
3
4
5
6
7
8
     Dim fso As Object
     Set fso = CreateObject("scripting.FileSystemObject")
     Dim ts As TextStream
     Set ts = fso.OpenTextFile(FolderName & filename, ForReading)
     Dim TextLine As String
     Do Until ts.AtEndOfStream
         TL = ts.ReadLine
..........



0



6874 / 2806 / 533

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

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

09.08.2017, 08:45

11

Ошибка в TextStream — что это, куда это… никто не знает.
Замените на Object



0



shanemac51

Модератор

Эксперт MS Access

11261 / 4592 / 739

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

Сообщений: 13,157

Записей в блоге: 4

09.08.2017, 09:21

12

у меня заработало, но после исправлений

Visual Basic
1
2
3
4
5
6
foldername = "O:путькпапке_кириллицей"
'''
pos = InStr(1, tl, pcname)
If pos > 0 And Len(tl) > 42 Then
Range("B" & rowcunt).Value = Right(tl, Len(tl) - 42)
End If



0



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

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

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Vba excel ошибка 429
  • Vba excel если ошибка то выполнить