Vba user defined type not defined word

I am trying to do some relatively simple copy and pasting from Excel 2007 into Word 2007. I’ve looked through this site and others, and keep getting hung up on the same thing- the third line n the code below keeps giving me the «User type note defined» error msg. I am really confused since I just lifted this from another solution (and had similar issues with other solutions I tried to lift). Could someone please educate me on what is causing the error, and why?

Sub ControlWord()
' **** The line below gives me the error ****
Dim appWD As Word.Application
' Create a new instance of Word & make it visible
Set appWD = CreateObject("Word.Application.12")
appWD.Visible = True

'Find the last row with data in the spreadsheet
FinalRow = Range("A9999").End(xlUp).Row
For i = 1 To FinalRow
    ' Copy the current row
    Worksheets("Sheet1").Rows(i).Copy
    ' Tell Word to create a new document
    appWD.Documents.Add
    ' Tell Word to paste the contents of the clipboard into the new document
    appWD.Selection.Paste
    ' Save the new document with a sequential file name
    appWD.ActiveDocument.SaveAs Filename:="File" & i
    ' Close this new word document
    appWD.ActiveDocument.Close
Next i
' Close the Word application
appWD.Quit
End Sub

SeanC's user avatar

SeanC

15.6k5 gold badges45 silver badges65 bronze badges

asked Jul 30, 2012 at 20:13

Tommy Z's user avatar

3

This answer was mentioned in a comment by Tim Williams.

In order to solve this problem, you have to add the Word object library reference to your project.

Inside the Visual Basic Editor, select Tools then References and scroll down the list until you see Microsoft Word 12.0 Object Library. Check that box and hit Ok.

From that moment, you should have the auto complete enabled when you type Word. to confirm the reference was properly set.

Community's user avatar

answered Jul 1, 2013 at 19:24

ForceMagic's user avatar

ForceMagicForceMagic

6,15212 gold badges68 silver badges88 bronze badges

2

As per What are the differences between using the New keyword and calling CreateObject in Excel VBA?, either

  • use an untyped variable:

    Dim appWD as Object
    appWD = CreateObject("Word.Application")
    

or

  • Add a reference to Microsoft Word <version> Object Library into the VBA project via Tools->References..., then create a typed variable and initialize it with the VBA New operator:

    Dim appWD as New Word.Application
    

    or

    Dim appWD as Word.Application
    <...>
    Set appWd = New Word.Application
    
    • CreateObject is equivalent to New here, it only introduces code redundancy

A typed variable will give you autocomplete.

answered Sep 1, 2017 at 17:27

ivan_pozdeev's user avatar

ivan_pozdeevivan_pozdeev

33.3k16 gold badges105 silver badges150 bronze badges

nataxa777

0 / 0 / 0

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

Сообщений: 26

1

07.06.2013, 14:12. Показов 42831. Ответов 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

971 / 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

6875 / 2807 / 533

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

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

18.02.2016, 22:15

4

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

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

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



0



  • 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 Sub

    Err_MailMergeButton_Click:
        MsgBox Err.Description
        Resume Exit_MailMergeButton_Click

       
    End Sub

    Can 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

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.

Понравилась статья? Поделить с друзьями:
  • Vba tools for excel
  • Vba to update sql from excel
  • Vba to kill excel
  • Vba to group rows in excel
  • Vba to color cells in excel