I am trying to save Word docs using Excel VBA, but I get the error
«ActiveX component can’t create object.»
When I debug, the error comes from the line: Set wrdApps = CreateObject("Word.Application")
.
It was working, then it started giving me this error.
Sub saveDoc()
Dim i As Integer
For i = 1 To 2661:
Dim fname As String
Dim fpath As String
With Application
.DisplayAlerts = False
.ScreenUpdating = False
.EnableEvents = False
End With
fname = ThisWorkbook.Worksheets(3).Range("H" & i).Value
fpath = ThisWorkbook.Worksheets(3).Range("G" & i).Value
Dim wrdApps As Object
Dim wrdDoc As Object
Set wrdApps = CreateObject("Word.Application")
'the next line copies the active document- the ActiveDocument.FullName
' is important otherwise it will just create a blank document
wrdApps.documents.Add wrdDoc.FullName
Set wrdDoc = wrdApps.documents.Open(ThisWorkbook.Worksheets(3).Range("f" & i).Value)
' do not need the Activate, it will be Activate
wrdApps.Visible = False
' the next line saves the copy to your location and name
wrdDoc.SaveAs "I:YunRTEMP DOC & PDF" & fname
'next line closes the copy leaving you with the original document
wrdDoc.Close
On Error GoTo NextSheet:
NextSheet:
Resume NextSheet2
NextSheet2:
Next i
With Application
.DisplayAlerts = True
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub
asked Jun 26, 2013 at 18:03
3
I had an issue when upgrading from Windows 7 to 10 when bringing my hoard of VBA scripts with me.
Still not sure what the root cause of the error is, but in the mean time this piece of code worked for me.
This is a workaround that limits the need to have Word (or Outlook/Excel) already in open (manually) state, but should allow your script to run if you have your references set.
Just change "CreateObject("
to "GetObject(, "
. This will tell the system to use an already open window.
The complete code to use would be:
Dim wrdApps As Object
Dim wrdDoc As Object
Set wrdApps = GetObject(, "Word.Application")
answered Jul 11, 2018 at 23:28
I recently had this happen to some code I had written. Out of nowhere (after running successfully for a few months), I would get the same Runtime Error ‘429’. This happened on two separate computers, the one I wrote and tested the code on months prior and the computer of the person who actually used the tool. It happened even though I used the original file on my machine and the user had been using his copy successfully for a few months, so I’m not convinced two separate files on two separate machines both got corrupted in the same manner. With that being said, I don’t have a good explanation of why this occurred. Mine would happen on a similar line of code:
Dim objFSO as Object
Set objFSO = CreateObj("Scripting.FileSystemObject")
I had the reference to the scripting library included and had done this successfully in the past.
I was able to fix the problem by changing from late to early binding on that object:
Dim objFSO as New Scripting.FileSystemObject
I have been switching everything over to early binding for some time now but this was some legacy code. A nice short little explanation on the difference between the two can be found here:
https://excelmacromastery.com/vba-dictionary/#Early_versus_Late_Binding
I’m not entirely certain why that fixed the problem, but hopefully it will help others in the future with similar issues.
answered Dec 5, 2019 at 16:19
user2731076user2731076
6391 gold badge6 silver badges20 bronze badges
Is wrdDoc initialised? Are you trying to use wrdDoc before the object has been Set?
wrdApps.documents.Add wrdDoc.FullName
Set wrdDoc = wrdApps.documents.Open(ThisWorkbook.Worksheets(3).Range("f" & i).Value)
Should the first line be ActiveDocument.FullName as in the comments? So:
wrdApps.documents.Add ActiveDocument.FullName
answered Sep 30, 2013 at 9:53
0
Check that you have the Microsoft Excel Object Library and the Microsoft Office Object Library ticked in Tools > References and that they have been registered.
If they are ticked, you may need to run Detect and Repair from the Excel Help menu to make sure that the Office installation hasn’t corrupted in any way.
answered Oct 3, 2013 at 10:10
In my case, the workbook appeared to be corrupted. Simply assigning a worksheet to a variable was throwing the error.
Dim ws as Worksheet
Set ws = ThisWorkbook.Worksheets("Data")
The workbook came directly from the client, so I’m not sure what they did with it, or how old it was but all the references appeared to be selected. Every other workbook with the same code was working correctly.
So to resolve the issue I copied the worksheets and modules to a new workbook and it worked without any issues.
Might not always be the best solution, but if you haven’t got any worksheets and modules, then it’s pretty easy.
answered Dec 3, 2019 at 8:31
Try this one.. i’ve encountered this a lot of time…
so I just run my excel by searching it (located on taskbar), then right click then «run as administrator»
or if you already created the excel file, open it from file>open>browse. avoid just double clicking the excel file to open directly.
answered Sep 9, 2018 at 8:49
ALFA Пользователь Сообщений: 243 |
Всем привет! |
Юрий М Модератор Сообщений: 60762 Контакты см. в профиле |
#2 30.09.2014 14:02:30
И где этот файл? |
||
Jack Пользователь Сообщений: 352 |
сохранить файл в формате .xlsx |
ALFA Пользователь Сообщений: 243 |
Вот если запускать файл уже при открытом приложении Excel, возникает сбой. |
Hugo Пользователь Сообщений: 23371 |
Чтоб всё проверить — нужен 2.htm |
ALFA Пользователь Сообщений: 243 |
вот он Прикрепленные файлы
|
Jack Пользователь Сообщений: 352 |
#7 30.09.2014 18:49:45 а если поменять в коде ЭтаКнига
на
именно на эту строчку иногда ругается |
||||
ALFA Пользователь Сообщений: 243 |
1/0 это модальное/не модальное, какое отношение имеет к делу? |
Jack Пользователь Сообщений: 352 |
у вас указан параметр showmodal = true. |
Юрий М Модератор Сообщений: 60762 Контакты см. в профиле |
Вам предлагают вариант — проверьте. Если ничего не изменится, значит не имеет)) |
ALFA Пользователь Сообщений: 243 |
#11 30.09.2014 19:05:06 Ошибка действительно пропала, но окно стало модальным и теперь невозможно выполнить следующее:
На фоне формы отображается эксель. |
||
Jack Пользователь Сообщений: 352 |
попробуйте тогда изменить параметр ShowModal в окне свойств юзерформы на False Изменено: Jack — 30.09.2014 19:10:53 |
ALFA Пользователь Сообщений: 243 |
|
Jack Пользователь Сообщений: 352 |
#14 30.09.2014 19:31:09 потестил.
приложение у меня скрывается. Изменено: Jack — 30.09.2014 19:31:26 |
||
ALFA Пользователь Сообщений: 243 |
У меня появляется ошибка, если приложение excel уже запущено(Открыт иной файл) на момент открытия файла, если я ставлю .show 0 то есть ошибка, если ставлю .show 1 то ошибка пропадает и application не скрывается. |
Doober Пользователь Сообщений: 2230 |
#16 30.09.2014 23:54:32
Все верно,код выполнится после закрытия формы.
Изменено: Doober — 01.10.2014 02:20:06 |
||||
bombowoz Пользователь Сообщений: 6 |
#17 25.11.2019 00:01:28 Доброго времени суток Всем. Год назад написал я макрос для Excel- файла с целью автоматизации деятельности своей и моих коллег. Суть макроса — запуск внешней ЕХЕ программы (самописаной) для получения от прибора данных и последующая интеграция данных в книгу Excel/
Основная проблема в том, что я не понимаю, почему перестало работать то, что полгода работало без проблем. Если-бы админы изменили что-то в политике безопасности, то у всех коллег одновременно перестало-бы работать. А так — через большие промежутки времени. Более того, что такого страшного в строке Где косяк? Почему перестало работать и как всё починить? Может есть другой способ запуска стороннего ЕХЕ-файла с параметрами (консольное приложение написано в CodeBlocks) и обязательным ожиданием ответного кода-завершения от него? (простой Shell не подходит)??? |
||
Юрий М Модератор Сообщений: 60762 Контакты см. в профиле |
#18 25.11.2019 00:06:03
А как это соотносится с данной темой (про ActiveX)? |
||
Hugo Пользователь Сообщений: 23371 |
Вообще скрипты vbs на этих машинах работают? Потому что бывает что это отключают из соображений безопасности, а как именно это реализовано — я не в курсе, может отключают на корню весь объект. |
БМВ Модератор Сообщений: 21650 Excel 2013, 2016 |
#20 25.11.2019 00:37:40
как правило блокируется запуск скрипта пользователем. Я б не стал горячится и отключать объект, так как полно системных скриптов, которые должны выполнятся, хотя бы даже установка принтеров через них сделана. а вот можно ли залочить Shell это вопрос мной не изученный. Как минимум яб проверил работу VBS, других его объектов например https://www.script-coding.com/WSH/FileSystemObject.html а уже потом бы решал. По вопросам из тем форума, личку не читаю. |
||
ZVI Пользователь Сообщений: 4338 |
#21 25.11.2019 02:06:52
В проекте установите ссылку на Tools — References — Windows Script Host Object Model и проверьте, работает ли такой код:
Если не работает, то проверьте свои права доступа (правый клик — свойства — Безопасность) на чтение и выполнение для файла C:WindowsSystem32wshom.ocx Изменено: ZVI — 25.11.2019 02:08:59 |
||||
bombowoz Пользователь Сообщений: 6 |
#22 25.11.2019 21:43:56
спасибо за участие Изменено: bombowoz — 25.11.2019 21:48:52 |
||
БМВ Модератор Сообщений: 21650 Excel 2013, 2016 |
Тут из запасников пришлось достать HTA и там wscript.Shell был , так в чистом виде в 10ке перестал работать, а если конвертить в exe то работает. По вопросам из тем форума, личку не читаю. |
bombowoz Пользователь Сообщений: 6 |
-э-э-э-э….. З.Ы.(извините, в VBA/VBS очень слаб, не пинайте ногами) |
БМВ Модератор Сообщений: 21650 Excel 2013, 2016 |
bombowoz, hta — ЭТО HTML Application. , то есть приложение которое работает с использованием движка браузера (в нутрях собственно HTML теги и миы или Java script. В чистом виде — означает ,что запускается HTA файл и, видимо, по соображениям безопасности в контенте этого процесса запрещен вызов SHELL, ну дабы зловреды не запустили чего. Блокировки объекта при вызове из VBS, VBA, я не замечал . По вопросам из тем форума, личку не читаю. |
bombowoz Пользователь Сообщений: 6 |
#26 26.11.2019 09:24:07
Проверил — работает на всех компах, если в чекбоксе (Tools — References — Windows Script Host Object Model) поставить птичку. Без птички не работает. P.S. А есть альтернатива запуска ЕХЕ помимо WshShell ? (чтобы можно было получать назад код завершения) |
||
bedvit Пользователь Сообщений: 2517 Виталий |
#27 26.11.2019 13:50:51
можно скомпилировать не ехе, а dll и запускать из VBA напрямую, не используя сторонние библиотеки. «Бритва Оккама» или «Принцип Калашникова»? |
||
ZVI Пользователь Сообщений: 4338 |
#28 26.11.2019 17:16:11
Если птички не жалко, то поставьте ее и используйте такой вариант кода:
Изменено: ZVI — 26.11.2019 17:16:35 |
||||
bombowoz Пользователь Сообщений: 6 |
#29 26.11.2019 17:52:51
Спасибо ещё раз — попробую. Отпишусь. |
||
bombowoz Пользователь Сообщений: 6 |
#30 27.11.2019 11:09:36 ZVI, — — работает.! |
- Remove From My Forums
-
Question
-
Excel and Access 2013. Windows 10
Excel file that runs the following VB code to pull info from a Access database.
Dim dbmain as DAO.Database
Set dbmain = OpenDatabase(dbpath)
VB codes work fine on multiple Windows 10 machine, but one. I get
«Run-time error ‘429’, ActiveX component can’t create object» on the OpenDatabase line.
Checked VBAProject — References, both the working and non-working machine have the same references check. Ran repair on Office 2013. Still getting the same error. I can browse and open the database manually.
Thanks in advance for your help.
Roget Luo
Answers
-
My suggestion would be to uninstall 64-bit Office and install 32-bit Office.
64-bit Office has far too many incompatibilities and hardly any advantages.
But apart from that, the Microsoft Office 15.0 Access database engine Object Library should work in 64-bit Office.
Regards, Hans Vogelaar (http://www.eileenslounge.com)
-
Marked as answer by
Wednesday, November 1, 2017 6:00 PM
-
Marked as answer by
- Remove From My Forums
-
Question
-
A DLL required by the object can’t be used, either because it can’t be found, or it was found but was corrupted.
Make sure all associated DLLs are available. For example, the Data Access Object (DAO) requires supporting DLLs that vary among platforms. You may have to rerun the setup program for such an object if that is what is causing this error.I am using Windows 10 and Office 2016 Excel visual basic.
How can I make sure all the associated DLLs are available?
How do I rerun the setup program for this object?
I am wishing to run this code:-
I am running windows 10 on notebook 64bit and subscribe to office 2016
Microsoft Excel 16
I get a ‘Run time error 429’
— ActiveX component can’t create object
when I run this code in Excel VBA.
Set objIE = New InternetExplorer
It should open a new instance of Internet Explorer, but the program halts with this error 429. But it appears the whole code doesn’t like the «obj» reference.
Thanks you in anticipation if anyone can help me.
Answers
-
-
Proposed as answer by
Sunday, June 26, 2016 2:58 PM
-
Marked as answer by
David_JunFeng
Monday, June 27, 2016 9:44 AM
-
Proposed as answer by
-
It should be InternetExplorer.Application instead of just InternetExplorer
Really? It get a compile error if I do so:
But when I set a reference to
Microsoft Internet Controls
{EAB22AC0-30C1-11CF-A7EB-0000C05BAE0B} 1.1
C:WindowsSysWOW64ieframe.dllthen this code works for me:
Option Explicit Sub Test() Dim objIE As InternetExplorer Set objIE = New InternetExplorer objIE.Visible = True End Sub
IMHO this issue is not related to the code but to windows, resp. the internet explorer itself.
So I suggest the OP should repair the internet explorer:
https://support.microsoft.com/en-us/kb/318378Andreas.
-
Edited by
Andreas Killer
Sunday, June 19, 2016 10:45 AM -
Proposed as answer by
David_JunFeng
Sunday, June 26, 2016 2:58 PM -
Marked as answer by
David_JunFeng
Monday, June 27, 2016 9:44 AM
-
Edited by
-
This code does what you want:
Option Explicit
Sub Test()
Dim ObjIE As ObjectSet ObjIE = CreateObject(«InternetExplorer.Application»)
‘…. (your code) ….
End Sub
Best regards, George
-
Proposed as answer by
David_JunFeng
Sunday, June 26, 2016 2:58 PM -
Marked as answer by
David_JunFeng
Monday, June 27, 2016 9:44 AM
-
Proposed as answer by
Run-time error 429 is a Visual Basic error often seen when creating instances in MS Office or other programs that depends or use Visual Basic. This error occurs when the Component Object Model (COM) cannot create the requested Automationobject, and the Automation object is, therefore, unavailable to Visual Basic. This error does not occur on all computers.
Many Windows users have reported experiencing over the years and over the many different iterations of the Windows Operating System that have been developed and distributed. In the majority of reported cases, Run-time error 429 rears its ugly head while the affected user is using a specific application on their Windows computer, and the error results in the affected application crashing and closing down abruptly.
Some users have also reported receiving this error when they try and run applications/add-ons designed on VB such as those provided by bloomberg and bintex.
Run-time error 429 has been the cause of worry across the many different versions of Windows that have existed, including Windows 10 – the latest and greatest in a long line of Windows Operating Systems. The most common victims of Run-time error 429 include Microsoft Office applications (Excel, Word, Outlook and the like), and Visual Basic sequence scripts.
The entirety of the error message that users affected by this problem see reads:
“Run-time error ‘429’: ActiveX component can’t create the object“
That being the case, this error is sometimes also referred to as ActiveX Error 429. The message accompanied by this error doesn’t really do much in the way of explaining its cause to the affected user, but it has been discovered that Run-time error 429 is almost always triggered when the affected application tries to access a file that does not exist, has been corrupted or simply hasn’t been registered on Windows for some reason. The file the application tries to access is integral to its functionality, so not being able to access it results in the application crashing and spitting out Run-time error 429.
Fixing Run-time error ‘429’: ActiveX component can’t create the object
Thankfully, though, there is a lot anyone affected by Run-time error 429 can do in order to try and get rid of the error and resolve the problem. The following are some of the absolute most effective solutions that you can use to push back when faced with Run-time error 429:
Solution 1: Perform an SFC scan
One of the leading culprits behind Run-time error 429 are system files applications need in order to function properly but which have somehow been corrupted. This is where an SFC scan comes in. The System File Checker utility is a built-in Windows tool designed specifically for the purpose of analyzing a Windows computer for corrupt or otherwise damaged system files, locating any that exist and then either repairing them or replacing them with cached, undamaged copies. If you are trying to get rid of Run-time error 429, running an SFC scan is definitely a first step in the right direction. If you are not familiar with the process of running an SFC scan on a Windows computer, simply follow this guide.
Solution 2: Re-register the affected application
If you are only running into Run-time error 429 while using a specific application on your computer, it is quite likely that you have fallen prey to the problem simply because the application in question has not been correctly configured on your computer and, therefore, is causing issues. This can quickly be remedied by simply re-registering the affected application with the onboard automation server the Windows Operating System has, after which any and all issues should be resolved on their own. To re-register the affected application on your computer, you need to:
- Make sure that you are logged into an Administrator account on your Windows computer. You are going to need administrative privileges to re-register an application on your computer.
- Determine the complete file path for the executable application file (.EXE file) belonging to the application affected by this problem. To do so, simply navigate to the directory on your computer the affected application was installed to, click on the address bar in the Windows Explorer window, copy over everything it contains to some place you can easily retrieve it from when you need it, and add the name of the file and its extension to the end of the file path. For example, if the application in question is Microsoft Word, the full file path will look something like:
C:Program Files (x86)Microsoft OfficeOffice12WINWORD.EXE - Press the Windows Logo key + R to open a Run dialog.
- Type in or copy over the full file path for the executable application file belonging to the application affected by Run-time error 429, followed by /regserver. The final command should look something like:
C:Program Files (x86)Microsoft OfficeOffice12WINWORD.EXE /regserver - Press Enter.
- Wait for the application in question to be successfully re-registered.
Once the application has been re-registered, be sure to launch and use it and check to see if Run-time error 429 still persists.
Solution 3: Re-register the file specified by the error message
In some cases, the error message affected users see with Run-time error 429 specifies a particular .OCX or .DLL file that the affected application could not access. If the error message does specify a file in your case, the specified file is simply not correctly registered in your computer’s registry. Re-registering the specified file might just be all you need to do in order to get rid of Run-time error 429. To re-register a file with your computer’s registry, you need to:
- Close any and all open applications.
- Make sure that you have the full name of the file specified by the error message noted down someplace safe.
- If you’re using Windows 8 or 10, simply right-click on the Start Menu button to open the WinX Menu and click on Command Prompt (Admin) to launch an elevated Command Prompt that has administrative privileges. If you’re using an older version of Windows, however, you are going to have to open the Start Menu, search for “cmd“, right-click on the search result titled cmd and click on Run as administrator to achieve the same result.
- Type regsvr32 filename.ocx or regsvr32 filename.dll into the elevated Command Prompt, replacing filename with the actual name of the file specified by the error message. For example, if the error message specified vbalexpbar4.ocx as the file that could not be accessed, what you type into the elevated Command Prompt will look something like:
regsvr32 vbalexpbar4.ocx - Press Enter.
Wait for the specified file to be successfully re-registered with your computer’s registry, and then check to see if you have managed to successfully get rid of Run-time error 429.
Solution 4: Reinstall Microsoft Windows Script (For Windows XP and Windows Server 2003 users only)
The purpose of Microsoft Windows Script on Windows XP and Windows Server 2003 is to allow multiple scripting languages to work simultaneously in perfect harmony, but a failed, incomplete or corrupted installation of the utility can result in a variety of different issues, Run-time error 429 being one of them. If you are experiencing Run-time error 429 on Windows XP or Windows Server 2003, there is a good chance that simply reinstalling Microsoft Windows Script will fix the problem for you. If you would like to reinstall Microsoft Windows Script on your computer, simply:
- Click here if you are using Windows XP or here if you are using Windows Server 2003.
- Click on Download.
- Wait for the installer for Microsoft Windows Script to be downloaded.
- Once the installer has been downloaded, navigate to the directory it was downloaded to and run it.
- Follow the onscreen instructions and go through the installer all the way through to the end to successfully and correctly install Microsoft Windows Script on your computer.
Once you have a correct installation of Microsoft Windows Script on your computer, check to see if Run-time error 429 still persists.
Kevin Arrows
Kevin Arrows is a highly experienced and knowledgeable technology specialist with over a decade of industry experience. He holds a Microsoft Certified Technology Specialist (MCTS) certification and has a deep passion for staying up-to-date on the latest tech developments. Kevin has written extensively on a wide range of tech-related topics, showcasing his expertise and knowledge in areas such as software development, cybersecurity, and cloud computing. His contributions to the tech field have been widely recognized and respected by his peers, and he is highly regarded for his ability to explain complex technical concepts in a clear and concise manner.