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
15.6k5 gold badges45 silver badges65 bronze badges
asked Jul 30, 2012 at 20:13
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.
answered Jul 1, 2013 at 19:24
ForceMagicForceMagic
6,20012 gold badges66 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 viaTools->References...
, then create a typed variable and initialize it with the VBANew
operator:Dim appWD as New Word.Application
or
Dim appWD as Word.Application <...> Set appWd = New Word.Application
CreateObject
is equivalent toNew
here, it only introduces code redundancy
A typed variable will give you autocomplete.
answered Sep 1, 2017 at 17:27
ivan_pozdeevivan_pozdeev
33.5k17 gold badges105 silver badges150 bronze badges
- Remove From My Forums
-
Вопрос
-
Здравствуйте!
Подскажите в чем ошибка. пытаюсь сделать в форме кнопку при нажатии которой должен открыться документ в Word.
при нажатии появляется ошибка «Compile error: User defined — type not defined» и выделяется строчка
Code Snippet
Dim app As Word.Application
в другой базе с такой же строчкой все документы открываются. может я не правильно делаю кнопку? как правильно сделать?
Спасибо за помощь, заранее!
Ответы
-
В редакторе VB выберите Tools->References и в открывшемся окне поставьте галку напротив Microsoft Word <версия>
postrelll Пользователь Сообщений: 7 |
#1 02.09.2016 12:23:58 Добрый день, столкнулся со следующей проблемой в 2016 офисе. Есть макрос, выполняющий роль заполнялки документов по шаблону. Выполняется макрос из excel файлика, среди шаблонов есть Word документы, соответсвенно приходится в самом макросе оперировать с этими word объектами через Word.Application. Макрос корректно работал на версии офиса 2010 и младше. Сейчас установили 2016 офис и возникла проблема — при выполнении одной из строк кода возникает ошибка
Начальная инициализация
Проблемная функция
Проблемная строка на которой светится ошибка 4605
Буду рад любой помощи |
||||||||
The_Prist Пользователь Сообщений: 14264 Профессиональная разработка приложений для MS Office |
А на этой строке нет ошибки? Как из Excel обратиться к другому приложению проблема в том, что Excel ничего не знает о константах Word-а, в том числе и про эту: wdReplaceAll Изменено: The_Prist — 02.09.2016 12:29:09 Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
postrelll Пользователь Сообщений: 7 |
#3 02.09.2016 12:43:05 The_Prist
То макрос выполняется без ошибок. Шаблон с Word документом сохраняется с нужным мне именем. Однако нужных мне замен в этом шаблоне не производится. ПОдключенные библиотеки |
||
Hugo Пользователь Сообщений: 23372 |
#4 02.09.2016 12:48:58 Вместо констант пишите явно значение этих констант.
Изменено: Hugo — 02.09.2016 13:00:20 |
||
postrelll Пользователь Сообщений: 7 |
Проблема решена — поменял формат шаблонов на .docx и переместил их с системного диска в документы пользователя. |
The_Prist Пользователь Сообщений: 14264 Профессиональная разработка приложений для MS Office |
#6 02.09.2016 13:51:39
не хотите Вы прислушиваться и читать…Она обязательно может всплыть в другой раз. Т.к. библиотека Word 16 может не подхватиться на более ранних. Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
||
postrelll Пользователь Сообщений: 7 |
The_Prist Проблема была в «безопасном режиме» шаблона, который открывался. В моем случае макрос открывал шаблон из указанного пути. В шаблоне в цикле делал замены в нужные места документов и затем сохранял шаблон под определенным именем. Ошибка изначально была связана с тем, что при открытии шаблона в безопасном режиме его невозможно редактировать, соответственно и делать замены в нём так же нельзя. А этот безопасный режим появился только в 2016 офисе (возможно и в 2013 он так же есть), поскольку в 2010 все открывалось нормально в обычном режиме. Стоит так же сказать, что шаблоны были в .doc формате для лучшей совместимости с более старыми офисами, поскольку макросом пользуются на самых разных ПК. Из-за этого и выползала ошибка. Плюс я изначально все шаблоны загонял в отдельную папку на диске С. Учитывая, что макрос сейчас запускается из-под WIn 10, проблему так же создавала встроенная защита системы, поскольку она любит подтверждать через UAC все процедуры перезаписи/удаления. Поэтому и перенес папку с шаблонами в документы пользователя. Изменено: postrelll — 02.09.2016 17:05:03 |
Сергей Редькин Пользователь Сообщений: 1 |
#8 19.01.2022 08:58:23 У меня была похожая проблема со вставкой неформатированных значений из ячеек в размеченные закладками места в Word. Ошибки периодически вылазили на этой строке:
Перенос файла шаблона в папку шаблонов по умолчанию не помог. Насколько понимаю проблемы возникают при вызове функций Word из VBA, запущенном в Excel, но до конца в причинах я так и не разобрался. Заменил Copy/Paste на вставку значения текстовой переменной. Самое интересное, что один Selection.Copy / Selection.PasteAndFormat (wdFormatPlainText) в самом конце макроса работает корректно, но как только вставляю в макрос несколько — вылазят ошибки.
Изменено: Сергей Редькин — 19.01.2022 10:39:43 |
||||
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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
Private Sub Выгрузка_Click() On Error GoTo Err_Выгрузка_Click Dim dDate As Date Dim z2000_010_04, z2000_010_05, z2000_010_06, z2000_010_07, z2000_010_08, z2000_010_09, z2000_010_10, z2000_010_11, z2000_010_12, z2000_010_13, z2000_010_14, z2000_010_15, z2000_010_16, z2000_010_17, z2000_010_18, z2000_010_19, z2000_010_20, z2000_010_21, z2000_010_22, z2000_010_23, z2000_010_24, z2000_010_25, z2000_010_26 As String 'Получаем шаблон — теперь из базы данных Dim oBOF As BoundObjectFrame Set oBOF = Otch.Controls("OLEObject1") oBOF = DLookup("[Шаблон]", "Шаблон", "[КодШаблон] = 1") oBOF.Verb = acOLEVerbOpen oBOF.Action = acOLEActivate 'Получаем ссылки на запущенный нами Word и открытый в нем документ Dim oWord As Object Set oWord = CreateObject("Word.Application") app.Visible = True app.Documents.Add strPathDot oWord.Visible = True oWord.ActiveWindow.WindowState = wdWindowStateMaximize oDoc.Activate 'Вставляем данные в закладки oDoc.Bookmarks.Item("z2000_010_04").Range.Text = Nz(z2000_010_04, "") oDoc.Bookmarks.Item("z2000_010_05").Range.Text = Nz(z2000_010_05, "") oDoc.Bookmarks.Item("z2000_010_06").Range.Text = Nz(z2000_010_06, "") oDoc.Bookmarks.Item("z2000_010_07").Range.Text = Nz(z2000_010_07, "") oDoc.Bookmarks.Item("z2000_010_08").Range.Text = Nz(z2000_010_08, "") oDoc.Bookmarks.Item("z2000_010_09").Range.Text = Nz(z2000_010_09, "") oDoc.Bookmarks.Item("z2000_010_10").Range.Text = Nz(z2000_010_10, "") oDoc.Bookmarks.Item("z2000_010_11").Range.Text = Nz(z2000_010_11, "") oDoc.Bookmarks.Item("z2000_010_12").Range.Text = Nz(z2000_010_12, "") oDoc.Bookmarks.Item("z2000_010_13").Range.Text = Nz(z2000_010_13, "") oDoc.Bookmarks.Item("z2000_010_14").Range.Text = Nz(z2000_010_14, "") oDoc.Bookmarks.Item("z2000_010_15").Range.Text = Nz(z2000_010_15, "") oDoc.Bookmarks.Item("z2000_010_16").Range.Text = Nz(z2000_010_16, "") oDoc.Bookmarks.Item("z2000_010_17").Range.Text = Nz(z2000_010_17, "") oDoc.Bookmarks.Item("z2000_010_18").Range.Text = Nz(z2000_010_18, "") oDoc.Bookmarks.Item("z2000_010_19").Range.Text = Nz(z2000_010_19, "") oDoc.Bookmarks.Item("z2000_010_20").Range.Text = Nz(z2000_010_20, "") oDoc.Bookmarks.Item("z2000_010_21").Range.Text = Nz(z2000_010_21, "") oDoc.Bookmarks.Item("z2000_010_22").Range.Text = Nz(z2000_010_22, "") oDoc.Bookmarks.Item("z2000_010_23").Range.Text = Nz(z2000_010_23, "") oDoc.Bookmarks.Item("z2000_010_24").Range.Text = Nz(z2000_010_24, "") oDoc.Bookmarks.Item("z2000_010_25").Range.Text = Nz(z2000_010_25, "") oDoc.Bookmarks.Item("z2000_010_26").Range.Text = Nz(z2000_010_26, "") DoCmd.OpenReport stoWord, acdDate Exit_Выгрузка_Click: Exit Sub Err_Выгрузка_Click: MsgBox Err.Description Resume Exit_Выгрузка_Click End Sub |
Summary
When you use the New operator or the CreateObject function in Microsoft Visual Basic to create an instance of a Microsoft Office application, you may receive the following error message:
Run-time error ‘429’: ActiveX component can’t create object
This error occurs when the Component Object Model (COM) cannot create the requested Automation object, and the Automation object is, therefore, unavailable to Visual Basic. This error does not occur on all computers.
This article describes how to diagnose and resolve common problems that may cause this error.
More Information
In Visual Basic, there are several causes of error 429. The error occurs if any of the following conditions is true:
-
There is a mistake in the application.
-
There is a mistake in the system configuration.
-
There is a missing component.
-
There is a damaged component.
To find the cause of the error, isolate the problem. If you receive the «429» error message on a client computer, use the following information to isolate and resolve the error in Microsoft Office applications.
Note Some of the following information may also apply to non-Office COM servers. However, this article assumes that you want to automate Office applications.
Examine the code
Before you troubleshoot the error, try to isolate a single line of code that may be causing the problem.
If you discover that a single line of code may be causing the problem, complete these procedures:
-
Make sure that the code uses explicit object creation.
Problems are easier to identify if they are narrowed down to a single action. For example, look for implicit object creation that’s used as one of the following.
Code sample 1
Application.Documents.Add 'DON'T USE THIS!!
Code sample 2
Dim oWordApp As New Word.Application 'DON'T USE THIS!! '... some other code oWordApp.Documents.Add
Both of these code samples use implicit object creation. Microsoft Office Word 2003 does not start until the variable is called at least one time. Because the variable may be called in different parts of the program, the problem may be difficult to locate. It may be difficult to verify that the problem is caused when the Application object is created or when the Document object is created.
Instead, you can make explicit calls to create each object separately, as follows.
Dim oWordApp As Word.Application Dim oDoc As Word.Document Set oWordApp = CreateObject("Word.Application") '... some other code Set oDoc = oWordApp.Documents.Add
When you make explicit calls to create each object separately, the problem is easier to isolate. This may also make the code easier to read.
-
Use the CreateObject function instead of the New operator when you create an instance of an Office application.
The CreateObject function closely maps the creation process that most Microsoft Visual C++ clients use. The CreateObject function also permits changes in the CLSID of the server between versions. You can use the CreateObject function with early-bound objects and with late-bound objects.
-
Verify that the «ProgID» string that is passed to
CreateObject is correct, and then verify that the «ProgID» string is version independent. For example, use the «Excel.Application» string instead of using the «Excel.Application.8» string. The system that fails may have an older version of Microsoft Office or a newer version of Microsoft Office than the version that you specified in the «ProgID» string. -
Use the Erl command to report the line number of the line of code that does not succeed. This may help you debug applications that cannot run in the IDE. The following code tells you which Automation object cannot be created (Microsoft Word or Microsoft Office Excel 2003):
Dim oWord As Word.Application Dim oExcel As Excel.Application On Error Goto err_handler 1: Set oWord = CreateObject("Word.Application") 2: Set oExcel = CreateObject("Excel.Application") ' ... some other code err_handler: MsgBox "The code failed at line " & Erl, vbCritical
Use the MsgBox function and the line number to track the error.
-
Use late-binding as follows:
Dim oWordApp As Object
Early-bound objects require their custom interfaces to be marshaled across process boundaries. If the custom interface cannot be marshaled during CreateObject or during New, you receive the «429» error message. A late-bound object uses the IDispatch system-defined interface that does not require a custom proxy to be marshaled. Use a late-bound object to verify that this procedure works correctly.
If the problem occurs only when the object is early-bound, the problem is in the server application. Typically, you can reinstall the application as described in the «Examine the Automation Server» section of this article to correct the problem.
Examine the automation server
The most common reason for an error to occur when you use CreateObject or New is a problem that affects the server application. Typically, the configuration of the application or the setup of the application causes the problem. To troubleshoot, use following methods:
-
Verify that the Office application that you want to automate is installed on the local computer. Make sure that you can run the application. To do this, click Start, click
Run, and then try to run the application. If you cannot run the application manually, the application will not work through automation. -
Re-register the application as follows:
-
Click Start, and then click Run.
-
In the Run dialog box, type the path of the server, and then append /RegServer to the end of the line.
-
Click OK.
The application runs silently. The application is re-registered as a COM server.
If the problem occurs because a registry key is missing, these steps typically correct the problem.
-
-
Examine the LocalServer32 key under the CLSID for the application that you want to automate. Make sure that the LocalServer32 key points to the correct location for the application. Make sure that the path name is in a short path (DOS 8.3) format. You do not have to register a server by using a short path name. However, long path names that include embedded spaces may cause problems on some systems.
To examine the path key that is stored for the server, start the Windows Registry Editor, as follows:
-
Click Start, and then click Run.
-
Type regedit, and then click OK.
-
Move to the HKEY_CLASSES_ROOTCLSID key.
The CLSIDs for the registered automation servers on the system are under this key.
-
Use the following values of the CLSID key to find the key that represents the Office application that you want to automate. Examine the LocalServer32 key of the CLSID key for the path.
Office server
CLSID key
Access.Application
{73A4C9C1-D68D-11D0-98BF-00A0C90DC8D9}
Excel.Application
{00024500-0000-0000-C000-000000000046}
Outlook.Application
{0006F03A-0000-0000-C000-000000000046}
PowerPoint.Application
{91493441-5A91-11CF-8700-00AA0060263B}
Word.Application
{000209FF-0000-0000-C000-000000000046}
-
Check the path to make sure that it matches the actual location of the file.
Note Short path names may seem correct when they are not correct. For example, both Office and Microsoft Internet Explorer (if they are installed in their default locations) have a short path that is similar to C:PROGRA~1MICROS~X (where
X is a number). This name may not initially appear to be a short path name.To determine whether the path is correct, follow these steps:
-
Click Start, and then click Run.
-
Copy the value from the registry, and then paste the value in the Run dialog box.
Note Remove the /automation switch before you run the application.
-
Click OK.
-
Verify that the application runs correctly.
If the application runs after you click OK, the server is registered correctly. If the application does not run after you click OK, replace the value of the LocalServer32 key with the correct path. Use a short path name if you can.
-
-
Test for possible corruption of the Normal.dot template or of the Excel.xlb resource file. Problems may occur when you automate Microsoft Word or Microsoft Excel if either the Normal.dot template in Word or the Excel.xlb resource file in Excel is corrupted. To test these files, search the local hard disks for all instances of Normal.dot or of Excel.xlb.
Note You may find multiple copies of these files. There is one copy of each of these files for each user profile that is installed on the system.
Temporarily rename the Normal.dot files or the Excel.xlb files, and then rerun your automation test. Word and Excel both create these files if they cannot find them. Verify that the code works. If the code works when a new Normal.dot file is created, delete the files that you renamed. These files are corrupted. If the code does not work, you must revert these files to their original file names to save any custom settings that are saved in these files.
-
Run the application under the Administrator account. Office servers require Read/Write access to the registry and to the disk drive. Office servers may not load correctly if your current security settings deny Read/Write access.
Examine the system
System configuration may also cause problems for the creation of out-of-process COM servers. To troubleshoot, use the following methods on the system on which the error occurs:
-
Determine whether the problem occurs with any out-of-process server. If you have an application that uses a particular COM server (such as Word), test a different out-of-process server to make sure that the problem is not occuring in the COM layer itself. If you cannot create an out-of-process COM server on the computer, reinstall the OLE system files as described in the «Reinstalling Microsoft Office» section of this article, or reinstall the operating system to resolve the problem.
-
Examine the version numbers for the OLE system files that manage automation. These files are typically installed as a set. These files must match build numbers. An incorrectly configured setup utility can mistakenly install the files separately. This causes the files to be mismatched. To avoid problems in automation, examine the files to make sure that the files builds are matched.
The automation files are located in the WindowsSystem32 directory. Examine the following files.
File name
Version
Date modified
Asycfilt.dll
10.0.16299.15
September 29, 2017
Ole32.dll
10.0.16299.371
March 29, 2018
Oleaut32.dll
10.0.16299.431
May 3, 2018
Olepro32.dll
10.0.16299.15
September 29, 2017
Stdole2.tlb
3.0.5014
September 29, 2017
To examine the file version, right-click the file in Windows Explorer, and then click Properties. Note the last four digits of the file version (the build number) and the date that the file was last modified. Make sure that these values are the same for all the automation files.
Note The following files are for Windows 10 Version 1709, build 16299.431. These numbers and dates are examples only. Your values may be different.
-
Use the System Configuration utility (Msconfig.exe) to examine the services and system startup for third-party applications that might restrict running code in the Office application
Note Disable the antivirus program only temporarily on a test system that is not connected to the network.
Alternatively, follow these steps in Outlook to disable third-party add-ins:
If this method resolves the problem, contact the third-party antivirus vendor for more information about an update to the antivirus program.
-
On the File menu, click Options, and then click Add-ins.
-
Click Manage COM add-ins, and then click Go.
Note The COM add-ins dialog box opens.
-
Clear the check box for any third-party add-in, and then click OK.
-
Restart Outlook.
-
Reinstall Office
If none of the previous procedures resolve the problem, remove and then reinstall Office.
For more information, see the following Office article:
Download and install or reinstall Office 365 or Office 2016 on a PC or Mac
References
For more information about Office automation and code samples, go to the following Microsoft website:
Getting started with Office development
Need more help?
Want more options?
Explore subscription benefits, browse training courses, learn how to secure your device, and more.
Communities help you ask and answer questions, give feedback, and hear from experts with rich knowledge.