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
48.1k140 gold badges49 silver badges78 bronze badges
asked Jun 17, 2014 at 10:34
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:
- 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. - 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 ZemensDavid Zemens
52.8k11 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
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
Olle89Olle89
6687 silver badges22 bronze badges
1
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:
- The values of the keys can be updated or changed later and
- 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.
- Goto the menu Tools-> References
- Select the library “Microsoft Scripting Runtime.” (This varies depending on the object used. Here the same dictionary object is considered for explanation purposes
- Click on the “OK” button and close the dialog
- 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.
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.
Астронавт 0 / 0 / 0 Регистрация: 02.12.2013 Сообщений: 19 |
||||
1 |
||||
17.03.2014, 15:04. Показов 29008. Ответов 9 Метки нет (Все метки)
Уважаемые, помогите, запарился…
Показывает ошибку «User-defined type not defined», красит первую строчку в желтый цвет, выделяет вторую Подключил следующие библиотеки: Я новичок в программировании, помогите пожалуйста, наверняка фигни понаписал
__________________
0 |
Заблокирован |
|
17.03.2014, 15:10 |
2 |
Dim As cnn As ADODB.Connection As — ключевое слово, напрягите фантазию, придумайте что-нибудь свое Добавлено через 1 минуту
2 |
Астронавт 0 / 0 / 0 Регистрация: 02.12.2013 Сообщений: 19 |
||||
17.03.2014, 15:50 [ТС] |
3 |
|||
As перед cnn появился после того, как вы оформили код как vb. У меня в коде его нет и не было.
Ошибка та же
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 |
|||
Спасибо! Данная ошибка решена
Теперь выдает ошибку «type mismatch»..
0 |
2783 / 715 / 106 Регистрация: 04.02.2011 Сообщений: 1,443 |
|
17.03.2014, 19:00 |
6 |
Сообщение было отмечено Астронавт как решение Решение Не-не-не. Вы объявлять должны ADODB, чтобы использовать язык SQL для доступа к БД. Если вам нужны объекты Access, его объектная модель, так и подключайте Access.
1 |
mobile 26772 / 14451 / 3192 Регистрация: 28.04.2012 Сообщений: 15,782 |
||||
18.03.2014, 02:21 |
7 |
|||
Сообщение было отмечено Астронавт как решение РешениеАстронавт, Вам нужно использовать DAO для доступа к объектам БД. Чтобы вызвать макрос Access из Excel, можно использовать такой код
1 |
0 / 0 / 0 Регистрация: 02.12.2013 Сообщений: 19 |
|
18.03.2014, 09:37 [ТС] |
8 |
mc-black, спасибо за разъяснения! Буду разбираться с этим!
0 |
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, еще вопросик
0 |
Содержание
- User-defined type not defined
- See also
- Support and feedback
- PRB: ADO: Compile Error: User-Defined Type Not Defined
- Symptoms
- Cause
- Resolution
- Status
- More Information
- 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.
Источник
- 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 SubErr_MailMergeButton_Click:
MsgBox Err.Description
Resume Exit_MailMergeButton_Click
End SubCan 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
-
Marked as answer by