Excel create object error

 

ALFA

Пользователь

Сообщений: 243
Регистрация: 13.09.2013

Всем привет!
Столкнулся с очень ужасной ошибкой, с ней просто невозможно работать. В файле есть макрос, который выполняется при запуске книги, он то выполняется то выскакивает эта ошибка. Подскажите как убить ошибку.

 

Юрий М

Модератор

Сообщений: 60570
Регистрация: 14.09.2012

Контакты см. в профиле

#2

30.09.2014 14:02:30

Цитата
ALFA пишет: В файле есть макрос

И где этот файл?

 

Jack

Пользователь

Сообщений: 352
Регистрация: 01.01.1970

сохранить файл в формате .xlsx  ;)

 

ALFA

Пользователь

Сообщений: 243
Регистрация: 13.09.2013

Вот если запускать файл уже при открытом приложении Excel, возникает сбой.

 

Hugo

Пользователь

Сообщений: 23249
Регистрация: 22.12.2012

Чтоб всё проверить — нужен 2.htm

 

ALFA

Пользователь

Сообщений: 243
Регистрация: 13.09.2013

вот он

Прикрепленные файлы

  • primer.zip (7.26 КБ)

 

Jack

Пользователь

Сообщений: 352
Регистрация: 01.01.1970

#7

30.09.2014 18:49:45

а если поменять в коде ЭтаКнига
строчку

Код
UserForm1.Show 0

на

Код
UserForm1.Show 1

именно на эту строчку иногда ругается

 

ALFA

Пользователь

Сообщений: 243
Регистрация: 13.09.2013

1/0 это модальное/не модальное, какое отношение имеет к делу?

 

Jack

Пользователь

Сообщений: 352
Регистрация: 01.01.1970

у вас указан параметр showmodal = true.
если я не ошибаюсь это связано с методом .Show
если .Show 1 «UserForm is modal. Default.»

 

Юрий М

Модератор

Сообщений: 60570
Регистрация: 14.09.2012

Контакты см. в профиле

 Вам предлагают вариант — проверьте. Если ничего не изменится, значит не имеет))

 

ALFA

Пользователь

Сообщений: 243
Регистрация: 13.09.2013

#11

30.09.2014 19:05:06

Ошибка действительно пропала, но окно стало модальным и теперь невозможно выполнить следующее:

Код
application.visible = false

На фоне формы отображается эксель.

 

Jack

Пользователь

Сообщений: 352
Регистрация: 01.01.1970

попробуйте тогда изменить параметр ShowModal в окне свойств юзерформы на False
оставив .Show 0
хотя лично я никогда не заморачивался оставлял по умолчанию и .Show тоже по умолчанию. (т.е. true)
и приложение скрывалось тоже

Изменено: Jack30.09.2014 19:10:53

 

ALFA

Пользователь

Сообщений: 243
Регистрация: 13.09.2013

 

Jack

Пользователь

Сообщений: 352
Регистрация: 01.01.1970

#14

30.09.2014 19:31:09

потестил.

Код
.showmodal = false 
.show 0

приложение у меня скрывается.

Изменено: Jack30.09.2014 19:31:26

 

ALFA

Пользователь

Сообщений: 243
Регистрация: 13.09.2013

У меня появляется ошибка, если приложение excel уже запущено(Открыт иной файл) на момент открытия файла, если я ставлю .show 0 то есть ошибка, если ставлю .show 1 то ошибка пропадает и application не скрывается.

 

Doober

Пользователь

Сообщений: 2201
Регистрация: 09.04.2013

#16

30.09.2014 23:54:32

Цитата
то ошибка пропадает и application не скрывается.

Все верно,код выполнится после закрытия формы.
А если так?

Код
Public Sub Workbook_Open()
Application.Visible = False
UserForm1.Show 1
End Sub 

Изменено: Doober01.10.2014 02:20:06

<#0>

 

bombowoz

Пользователь

Сообщений: 6
Регистрация: 24.11.2019

#17

25.11.2019 00:01:28

Доброго времени суток Всем.
продолжу в этой теме….     …….. про WshShell

Год назад написал я макрос для Excel- файла с целью автоматизации деятельности своей и моих коллег. Суть макроса — запуск внешней ЕХЕ программы (самописаной) для получения от прибора данных и последующая интеграция данных в книгу Excel/
Файл с макросом работал полгода на пяти разных компьютерах (Win7, Win10, разные версии офиса…). Потом на одном компе при запуске макроса стала выскакивать ошибка 429.Всегда. Через месяц — на втором компе «поломалось»/ Ещё через два месяца перестало работать на третьем. На оставшихся двух пока работает.
Компы «корпоративные» и админятся очень издалека…. обновления ОС и офиса выполняются согласно корпоративной политике (автоматически). Пользователи сами ничего в настройках не меняли.
Текст макроса прост и процедура запуска взята копипастом на просторах интернета:

Код
Range("C20").Select
ActiveCell.FormulaR1C1 = 255
Set WshShell = CreateObject("WScript.Shell")                              <<<< на эту строку ругается дебагер и подсвечивает её жёлтым
intReturn = WshShell.Run("C:ABCGetData.exe X", 0, True)
Range("C20").Select
ActiveCell.FormulaR1C1 = intReturn

Основная проблема в том, что я не понимаю, почему перестало работать то, что полгода работало без проблем. Если-бы админы изменили что-то в политике безопасности, то у всех коллег одновременно перестало-бы работать. А так — через большие промежутки времени. Более того, что такого страшного в строке
Set WshShell = CreateObject(«WScript.Shell»). Судя по статьям в интернете — это нечто стандартное и применяется миллионными тиражами….
Именно на ней затыкается макрос и подсвечивается она в дебагере. То есть до запуска моей программы самописаной дело не доходит.
Прочитал весь интернет :(  убил уже наверное часов сто на это. Ничего не нашёл . Всякие
Dim WshShell As Object   дописывал, ….
VBA.CreateObject не меняет ничего….
/RegServer  исполнял ….
HKEY_CLASSES_ROOTCLSID  смотрел….
на одном компе переустановили офис (365) — не помогло;

Где косяк? Почему перестало работать и как всё починить?

Может есть другой способ запуска стороннего ЕХЕ-файла с параметрами (консольное приложение написано в CodeBlocks) и обязательным ожиданием ответного кода-завершения от него? (простой Shell не подходит)???

 

Юрий М

Модератор

Сообщений: 60570
Регистрация: 14.09.2012

Контакты см. в профиле

#18

25.11.2019 00:06:03

Цитата
bombowoz написал:
Суть макроса — запуск внешней ЕХЕ программы

А как это соотносится с данной темой (про ActiveX)?

 

Hugo

Пользователь

Сообщений: 23249
Регистрация: 22.12.2012

Вообще скрипты vbs на этих машинах работают? Потому что бывает что это отключают из соображений безопасности, а как именно это реализовано — я не в курсе, может отключают на корню весь объект.

 

БМВ

Модератор

Сообщений: 21376
Регистрация: 28.12.2016

Excel 2013, 2016

#20

25.11.2019 00:37:40

Цитата
Hugo написал:
бывает что это отключают из соображений безопасности,

как правило блокируется запуск скрипта пользователем. Я б не стал горячится и отключать объект, так как полно системных скриптов, которые должны выполнятся, хотя бы даже установка принтеров через них сделана.  а вот можно ли залочить Shell это вопрос мной не изученный. Как минимум яб проверил работу VBS, других его объектов например

https://www.script-coding.com/WSH/FileSystemObject.html

а уже потом бы решал.

По вопросам из тем форума, личку не читаю.

 

ZVI

Пользователь

Сообщений: 4328
Регистрация: 23.12.2012

#21

25.11.2019 02:06:52

Цитата
bombowoz написал: Set WshShell = CreateObject(«WScript.Shell»)   <<<< на эту строку ругается дебагер

В проекте установите ссылку на Tools — References — Windows Script Host Object Model и проверьте, работает ли такой код:

Код
Sub Test()
  ' Reference: Tools - References - Windows Script Host Object Model
  ' File: C:WindowsSystem32wshom.ocx
  Dim WshShell As IWshRuntimeLibrary.WshShell
  Set WshShell = New IWshRuntimeLibrary.WshShell
  WshShell.Popup "Hi!"
End Sub

Если не работает, то проверьте свои права доступа (правый клик — свойства — Безопасность) на чтение и выполнение для файла C:WindowsSystem32wshom.ocx

Изменено: ZVI25.11.2019 02:08:59

 

bombowoz

Пользователь

Сообщений: 6
Регистрация: 24.11.2019

#22

25.11.2019 21:43:56

Цитата
ZVI написал:
…проверьте, работает ли такой код…

спасибо за участие
— завтра попробую на том компе, где перестал работать макрос…
( на моём ноуте, что под рукой, проблема пока не всплывала, хотя у меня на ноуте птички нет на пункте «Windows Script Host Object Model»  -> макрос работает без проблем….)

Изменено: bombowoz25.11.2019 21:48:52
(дополнено)

 

БМВ

Модератор

Сообщений: 21376
Регистрация: 28.12.2016

Excel 2013, 2016

Тут из запасников пришлось достать HTA и там wscript.Shell  был , так в чистом виде в 10ке перестал работать, а если конвертить в exe то работает.

По вопросам из тем форума, личку не читаю.

 

bombowoz

Пользователь

Сообщений: 6
Регистрация: 24.11.2019

-э-э-э-э…..
Моё внимание привлекла фраза «в чистом виде перестал работать» — это значит, не только у меня «поломалось»?

З.Ы.(извините, в VBA/VBS очень слаб, не пинайте ногами)

 

БМВ

Модератор

Сообщений: 21376
Регистрация: 28.12.2016

Excel 2013, 2016

bombowoz,  hta  — ЭТО HTML Application. , то есть приложение которое работает с использованием движка браузера (в нутрях собственно HTML теги и миы или Java script.  В чистом виде — означает ,что запускается HTA файл и, видимо, по соображениям безопасности в контенте этого процесса запрещен вызов SHELL, ну дабы зловреды не запустили чего.  Блокировки объекта при вызове из VBS, VBA, я не замечал .

По вопросам из тем форума, личку не читаю.

 

bombowoz

Пользователь

Сообщений: 6
Регистрация: 24.11.2019

#26

26.11.2019 09:24:07

Цитата
ZVI написал:
проверьте, работает ли такой код

Проверил — работает на всех компах, если в чекбоксе (Tools — References — Windows Script Host Object Model) поставить птичку. Без птички не работает.
(Мой файл на моём компе работает из без этой птички)

P.S. А есть альтернатива запуска ЕХЕ помимо WshShell ? (чтобы можно было получать назад код завершения)

 

bedvit

Пользователь

Сообщений: 2477
Регистрация: 02.04.2015

Виталий

#27

26.11.2019 13:50:51

Цитата
bombowoz написал:
P.S. А есть альтернатива запуска ЕХЕ помимо WshShell ? (чтобы можно было получать назад код завершения)

можно скомпилировать не ехе, а dll и запускать из VBA напрямую, не используя сторонние библиотеки.

«Бритва Оккама» или «Принцип Калашникова»?

 

ZVI

Пользователь

Сообщений: 4328
Регистрация: 23.12.2012

#28

26.11.2019 17:16:11

Цитата
bombowoz написал: …работает на всех компах … Без птички не работает.

Если птички не жалко, то поставьте ее и используйте такой вариант кода:

Код
Sub Test()
  ' Reference: Tools - References - Windows Script Host Object Model
  ' File: C:WindowsSystem32wshom.ocx
  Dim intReturn
  Dim WshShell As IWshRuntimeLibrary.WshShell
  Set WshShell = New IWshRuntimeLibrary.WshShell
  Range("C20").Value = 255
  intReturn = WshShell.Run("C:ABCGetData.exe X", 0, True)
  Range("C20").Value = intReturn
End Sub

Изменено: ZVI26.11.2019 17:16:35

 

bombowoz

Пользователь

Сообщений: 6
Регистрация: 24.11.2019

#29

26.11.2019 17:52:51

Цитата
ZVI написал:
такой вариант кода

Спасибо ещё раз — попробую. Отпишусь.

 

bombowoz

Пользователь

Сообщений: 6
Регистрация: 24.11.2019

#30

27.11.2019 11:09:36

ZVI,  — — работает.!
Как говорится — «ты сделал мой ноябрь».
Спасибо тебе мил человек. Дай тебе Бог здоровья.

Содержание

  1. Createobject excel application ошибка
  2. You receive run-time error 429 when you automate Office applications
  3. Summary
  4. More Information
  5. Examine the code
  6. Examine the automation server
  7. Examine the system
  8. Возникновение ошибки выполнения 429 при автоматизации приложений Microsoft Office
  9. Аннотация
  10. Дополнительная информация
  11. Проверка кода
  12. Проверка сервера автоматизации
  13. Проверка системы

Createobject excel application ошибка

Здесь обсуждаются вопросы по языку Visual Basic 1-6 (а так же по схожим языкам, как, например, PowerBASIC).
Вопросы по Visual Basic .NET (это который входит в состав Visual Studio 2002/2003/2005/2008+, для тех, кто не в курсе) обсуждаются в разделе .NET.

Обратите внимание:
1. Прежде чем начать новую тему или отправить сообщение, убедитесь, что Вы не нарушаете правил форума!
2. Обязательно воспользуйтесь поиском. Возможно, Ваш вопрос уже обсуждали. Полезные ссылки приведены ниже.
3. Темы с просьбой выполнить какую-либо работу за автора в этом разделе не обсуждаются. Студенты, вам сюда: ПОМОЩЬ СТУДЕНТАМ !
4. Используйте теги [ code=vba ] . текст программы. [ /code ] для выделения текста программы подсветкой.
5. Помните, здесь телепатов нет. Формулируйте свой вопрос максимально грамотно и чётко: Как правильно задавать вопросы
6. Запрещено отвечать в темы месячной (и более) давности, без веских на то причин.

Полезные ссылки:
FAQ Сайта FAQ Раздела Кладовка Наши Исходники API-Guide Поиск по Разделу MSDN Library Online Google
Ваше мнение о модераторах: SCINER, B.V.

Источник

You receive run-time error 429 when you automate Office applications

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.

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.

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):

Use the MsgBox function and the line number to track the error.

Use late-binding as follows:

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.

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.

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

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.

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.

Источник

Возникновение ошибки выполнения 429 при автоматизации приложений Microsoft Office

Аннотация

При использовании в Microsoft Visual Basic оператора New или функции CreateObject для создания экземпляра приложения Microsoft Office может появиться приведенное ниже сообщение об ошибке.

Ошибка времени выполнения «429»: компоненту ActiveX не удается создать объект

Эта ошибка возникает, если com-модель компонента не может создать запрошенный объект службы автоматизации, и поэтому объект службы автоматизации недоступен для Visual Basic. Эта ошибка возникает не на всех компьютерах.

В этой статье описывается, как диагностировать и устранять распространенные проблемы, которые могут вызвать эту ошибку.

Дополнительная информация

В Visual Basic существует несколько причин ошибки 429. Ошибка возникает, если выполняется одно из следующих условий:

Наличие ошибки в приложении.

Наличие ошибки в конфигурации системы.

Отсутствие какого-либо компонента.

Наличие поврежденного компонента.

Чтобы найти причину возникновения ошибки, необходимо изолировать проблему. Если на клиентском компьютере появляется сообщение об ошибке «429», используйте следующие сведения, чтобы изолировать и устранить ошибку в приложениях Microsoft Office.

Примечание Некоторые из приведенных ниже сведений также могут применяться к COM-серверам, отличным от Office. Однако в данной статье предполагается, что ошибка связана с автоматизацией приложений Microsoft Office.

Проверка кода

Перед устранением ошибки попробуйте изолировать одну строку кода, которая может быть причиной проблемы.

Если вы обнаружите, что одна строка кода может вызвать проблему, выполните следующие процедуры:

Убедитесь, что код использует явное создание объекта.

Проблемы легче выявить, если они сужаются до одного действия. Например, найдите неявное создание объекта, которое используется в качестве одного из следующих вариантов.

В обоих примерах используется неявное создание объекта. Microsoft Office Word 2003 не запускается до первого вызова переменной. Поскольку код вызова переменной может быть расположен в различных частях программы, локализация проблемы может оказаться непростой задачей. Может быть трудно убедиться, что проблема вызвана при создании объекта Application или при создании объекта Document .

Вместо этого можно выполнять явные вызовы для создания каждого объекта отдельно, как показано ниже.

При использовании явных вызовов для создания каждого объекта по отдельности изолировать проблему легче. Это также может сделать код более удобным для чтения.

При создании экземпляра приложения Office используйте функцию CreateObject вместо оператора New.

Функция CreateObject тесно сопоставляет процесс создания, используемый большинством клиентов Microsoft Visual C++. Функция CreateObject также позволяет изменять идентификатор CLSID сервера между версиями. Функцию CreateObject можно использовать с объектами с ранней привязкой и с объектами с поздним связыванием.

Убедитесь, что строка ProgID, передаваемая
в CreateObject, правильна, а затем убедитесь, что строка ProgID не зависит от версии. Например, используйте строку «Excel.Application» вместо строки «Excel.Application.8». В системе, где возникает проблема, может быть установлена более старая или более новая версия Microsoft Office, отличная от версии, указанной в строке «ProgID».

Используйте команду Erl , чтобы сообщить номер строки кода, которая не завершается успешно. Это может облегчить отладку приложений, которые не запускаются в интегрированной среде разработки. Следующий код указывает, какой объект службы автоматизации нельзя создать (Microsoft Word или Microsoft Office Excel 2003):

Для отслеживания ошибки используйте функцию MsgBox и номер строки.

Используйте позднюю привязку следующим образом:

Для объектов с ранней привязкой необходимо, чтобы их настраиваемые интерфейсы были маршалированы через границы процессов. Если пользовательский интерфейс не может быть маршалирован во время CreateObject или Во время создания, вы получите сообщение об ошибке «429». Объект с поздней привязкой использует определенный системой интерфейс IDispatch, который не требует маршалирования настраиваемого прокси. Используйте объект с поздним связыванием, чтобы убедиться, что эта процедура работает правильно.

Если проблема возникает только при ранней привязке объекта, проблема возникает в серверном приложении. Как правило, чтобы устранить проблему, достаточно переустановить приложение, как описано в разделе «Проверка сервера автоматизации» данной статьи.

Проверка сервера автоматизации

Наиболее распространенной причиной возникновения ошибки при использовании CreateObject или New является проблема, которая влияет на серверное приложение. Обычно причиной возникновения проблемы является установка или конфигурация приложения. Для устранения неполадок используйте следующие методы:

Убедитесь в том, что приложение Microsoft Office, которое необходимо автоматизировать, установлено на локальном компьютере. Убедитесь в возможности запуска приложения. Для этого нажмите кнопку Пуск, нажмите кнопку
Выполнить, а затем попробуйте запустить приложение. Если приложение не запускается вручную, автоматизировать его нельзя.

Перерегистрируйте приложение описанным ниже образом.

Нажмите кнопку Пуск, а затем — Выполнить.

В диалоговом окне Выполнить введите путь к серверу и в конце строки добавьте параметр /RegServer.

Нажмите кнопку ОК.

Приложение выполняется автоматически. Приложение будет перерегистрировано как COM-сервер.

Если причиной возникновения проблемы является отсутствие раздела реестра, в большинстве случаев выполнение перечисленных ниже действий приводит к устранению проблемы.

Проверьте раздел LocalServer32 в разделе CLSID приложения, которое необходимо автоматизировать. Убедитесь в том, что раздел LocalServer32 указывает на правильное местоположение приложения. Проверьте, чтобы путь был указан в кратком формате (DOS 8.3). Сервер не обязательно регистрировать с использованием краткого пути. Однако длинные пути, включающие пробелы, в некоторых системах могут являться причиной возникновения проблем.

Чтобы изучить ключ пути, хранящийся для сервера, запустите редактор реестра Windows следующим образом:

Нажмите кнопку Пуск, а затем — Выполнить.

Введите regedit и нажмите кнопку ОК.

Перейдите в раздел HKEY_CLASSES_ROOTCLSID.

Идентификаторы CLSID для зарегистрированных серверов автоматизации в системе находятся под этим ключом.

Чтобы найти раздел, представляющий приложение Microsoft Office, которое необходимо автоматизировать, используйте приведенные ниже значения раздела CLSID. Поверьте в разделе CLSID путь, указанный в разделе LocalServer32.

Проверьте путь, чтобы убедиться, что он соответствует фактическому расположению файла.

Примечание. Краткие пути могут иногда казаться правильными ошибочно. Например, Office и Microsoft Internet Explorer (если они установлены в расположениях по умолчанию) имеют короткий путь, аналогичный C:PROGRA

X (где
X — это число). Этот путь может сначала не показаться кратким путем.

Чтобы определить, правильный ли путь, выполните следующие действия.

Нажмите кнопку Пуск, а затем — Выполнить.

Скопируйте значение из реестра и вставьте его в поле диалогового окна Выполнить.

Примечание Перед запуском приложения удалите параметр /automation .

Нажмите кнопку ОК.

Проверьте правильность запуска приложения.

Если приложение запускается после нажатия кнопки ОК, сервер зарегистрирован правильно. Если приложение не запускается после нажатия кнопки ОК, замените значение ключа LocalServer32 правильным путем. По возможности используйте краткий путь.

Проверьте шаблон Normal.dot или файл ресурсов Excel.xlb на предмет возможного повреждения. Проблемы при автоматизации Microsoft Word или Microsoft Excel могут возникать вследствие повреждения шаблона Normal.dot в Microsoft Word или файла ресурсов Excel.xlb в Microsoft Excel. Чтобы протестировать эти файлы, найдите на локальных жестких дисках все экземпляры Normal.dot или Excel.xlb.

Примечание Вы можете найти несколько копий этих файлов. Для каждого профиля пользователя, установленного в системе, имеется одна копия каждого из этих файлов.

Временно переименуйте файлы Normal.dot или Excel.xlb, а затем повторно запустите тест автоматизации. Если Microsoft Word и Microsoft Excel не находят эти файлы, они создают их снова. Убедитесь, что код работает. Если при создании нового файла Normal.dot код работает, удалите переименованные файлы. Эти файлы повреждены. Если код не работает, необходимо вернуть эти файлы в исходные имена файлов, чтобы сохранить все пользовательские параметры, сохраненные в этих файлах.

Запустите приложение под учетной записью администратора. Серверам Office требуется доступ на чтение и запись к реестру и диску. Серверы Office могут загружаться неправильно, если текущие параметры безопасности запрещают доступ на чтение и запись.

Проверка системы

Конфигурация системы также может вызвать проблемы при создании внепроцессных COM-серверов. Для устранения неполадок используйте следующие методы в системе, в которой произошла ошибка:

Определите, возникает ли проблема с каким-либо сервером вне процесса. Если у вас есть приложение, использующее определенный COM-сервер (например, Word), протестируйте другой внепроцессный сервер, чтобы убедиться, что проблема не возникает на самом уровне COM. Если вы не можете создать внепроцессный COM-сервер на компьютере, переустановите системные файлы OLE, как описано в разделе «Переустановка Microsoft Office» этой статьи, или переустановите операционную систему, чтобы устранить проблему.

Проверьте номера версий системных файлов OLE, которые управляют автоматизацией. Эти файлы обычно устанавливаются в наборе. Номера сборки этих файлов должны совпадать. Неправильно настроенная программа установки может по ошибке установить файлы отдельно. В этом случае файлы не будут сочетаться. Чтобы избежать проблем с автоматизацией, проверьте файлы, чтобы убедиться, что сборки файлов совпадают.

Файлы автоматизации находятся в каталоге WindowsSystem32. Проверьте перечисленные ниже файлы.

Источник

mentos_has_arisen

0 / 0 / 0

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

Сообщений: 243

1

13.04.2011, 15:17. Показов 7188. Ответов 3

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


Студворк — интернет-сервис помощи студентам

Visual Basic
1
2
3
4
Dim objXL As Object
strPath = CStr('D:ClientReportsReportsBalans.xls')
Set objXL = GetObject(strPath, 'Excel.Application')
Set objXL = GetObject('D:ClientReportsReportsBalans.xls', 'Excel.Application')

на 3-й строке выдает ошибку..
File name or Class Name not found

меняю строку на

Visual Basic
1
Set objXL = GetObject(, 'Excel.Application')

выдает ошибку:
ActiveX component can’t create object

Соль конечно не в этом.. GetObject посоветовали использовать для того, чтоб при обращении к Excel.Application не вбивать его в задачник.. ато сколько нажимаешь кнопку, столько и остается хвостов…
помогите пожалуйста, неделю в болоте увяз.. (((



0



90 / 37 / 14

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

Сообщений: 429

13.04.2011, 19:17

2

Если в Excel’е открыть файл (например С:1.xls), а потом открыть файл с именем 1.xls, то появится сообщение — нельзя, такой файл уже есть.
Вы открываете файл (судя по коду тот же) два раза — вот и ошибка.



0



Димит

90 / 37 / 14

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

Сообщений: 429

13.04.2011, 21:32

3

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
Private Xl As Excel.Application
Sub qwe()
On Error GoTo Errlabel
Set Xl = GetObject(, 'Excel.Application')
 
Exit Sub
Errlabel:
If Err.Number = 10 Then
   Set Xl = CreateObject('Excel.Application') 
End If
End Sub

И ещё надо установить ссылку на библиотеку Microsoft Excel Object Library



0



Димит

90 / 37 / 14

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

Сообщений: 429

13.04.2011, 21:35

4

что-то не то загнал. Правильно:

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Private Xl As Excel.Application
Sub qwe()
On Error GoTo Errlabel
Set Xl = GetObject(, 'Excel.Application')
    With Xl
        .Visible = True
        .
        .
    End With
Exit Sub
Errlabel:
    If Err.Number = 429 Then
       Set Xl = CreateObject('Excel.Application')
       Resume Next
    End If
    MsgBox Err.Description
End Sub

Кстати, а как на этом форуме исправить своё сообщение?



0



  • 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

  • Remove From My Forums
  • Question

  • Hi All,

    I am getting error while creating Excel object when running the application from a shered network drive. It is working fine when running from local. These are the codes.

    Private ExcelObj As Excel.Application

    ExcelObj = New Excel.Application() — getting exception at this line.

    This is the error message:

    System.UnauthorizedAccessException: Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80070005.

    Any idea how to resolve this. Please guide me.

    Thank you.

Answers

  • Thank you pclement  for your reply.

    I have managed to resolve the issue by changing the security settings of Microsoft Excel Application in DCOM Config.

    for those who may need this info, here is what I have done.

    goto Controlpanel —> Administrative tools—>Component Services —>computers —> myComputer —>DCOM Config —> Microsoft Excel Application.

    right click to get properties dialog. Goto Security tab and customize permissions accordingly.

    Thanks & Regards.

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

Community's user avatar

asked Jun 26, 2013 at 18:03

user2525309's user avatar

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")

SeeYouInDisneyland's user avatar

answered Jul 11, 2018 at 23:28

user64773's user avatar

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

user2731076's user avatar

user2731076user2731076

6091 gold badge6 silver badges19 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

Simon Shirley's user avatar

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

Simon Shirley's user avatar

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

Sam Martin's user avatar

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

Marvin Nario Machitar's user avatar

Avatar of coronoahcoro

coronoahcoro

Flag for United States of America asked on 7/16/2012

I wrote a LotusScript agent that create an Excel report from a Lotus Notes database. During the testing I run the agent from from the Action Bar from my Lotus Notes client and it is working and producing the report just fine. When I scheduled the agent to run on the server, the agent did not finish and on the log.nsf, I see ‘Automation object error’.

How do I fix the error?

Lotus IBM

Avatar of undefined

...
Print "Before creating Excel Object"
Set xlApp = CreateObject("Excel.Application")
Print "Create Object OK"
xlApp.Workbooks.Add
Print "Add Workbooks OK"
xlApp.ReferenceStyle = 2
Print "Add Reference Style OK"
xlApp.DisplayAlerts = False
Print "Add Display Alert OK"
Set xlSheet = xlApp.Workbooks(1).Worksheets(1)
Print "Add Worksheet OK"

Open in new window

The code throws an error when it hits xlApp.Workbooks.Add

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.

View this solution by signing up for a free trial.

Members can start a

7-Day free trial

and enjoy unlimited access to the platform.

As Sjef suggested, I guess that Excel is not installed on the server.

Since most admins aren’t very keen on having MS Office (or other non-Domino stuff) installed on «their» Domino server, I often choose to create the xls file in html format.

Just save your current Excel file as html and look at its sourcecode. You can produce the same output yourself by just using «open», «print #» and «close #». You may even leaveparts of the original code (xml / styles) out.

It’ll work from a scheduled agent as well as actions. It’ll even work in web apps and you can still freeze panes, predefine auto filter etc.

1. Windows Server 2008 R2
2. It was not, now it is. Sorry my mistake.
3. Yes
4. You mean who sign the agent? Currently it is me, but will change to server’s id

Now, after Installed Excel, I did not get Automation Object error but

… error message: Microsoft Office Excel: SaveAs method of Workbook class failed

Below is the code that I use for saving the Excel file

...
xlApp.ActiveWorkbook.SaveAs file_Path, 56
xlApp.Quit
...

Open in new window

4. No, that’s not what I meant. When the server runs as a service, without a user account specified, it runs under a System account that has little or no privileges.

Most likely cause: the server has no access to file_Path.

Suggestion: use c:Temp as file_path, and include a simple test to find out if the server is allowed to write a file in file_path.

I use the path below to save the Excel file:

file_Path = "C:WindowsSysWOW64configsystemprofileDesktop" & "WO_Pending_Approval_" & Year(Now()) & "_" & Month(Now()) & _
	"_" & Day(Now()) & "_Terr" & terr & ".xls"

Open in new window

and SYSTEM user account has a Full Control over the folder, but still the same error.

I will try your Temp folder suggestion, sjef.

@CRAK
The users specified that they want it in Excel file. If I understand your suggestion, then I just send the HTML file? That is not going to work on my case.

My standard «approach» is: stuff Excel, just create a .csv file ;-)

I wish you are my manager ;-) Originally it was created in CSV, but I was told that it was not pretty

No luck with C:Temp either?

What is the intended result? What if you send the users a URL to the Domino server, and when they click it they get an Excel screen in the browser with the data they need? If they want to save the file, they can do that. Could that be the idea?

No luck with C:Temp either. Does it matter that the Excel version that I put on the server is 2003 version?

The intended result is an Excel file that is sent to users email.

I am not quite sure about the idea that you mention sjef. How do I start on doing that?

ok seriously yes that is the problem. I am using MS Excel 2003. The format is 43 instead of 56

You can develop a web agent that sends data to the user’s browser in «excel» format: html code that Excel interprets as a spreadsheet.

Example:
— http://www.botstation.com/code/view2excelweb.php
— http://www.codestore.net/store.nsf/unid/EPSD-559R3S/ (rather old, but explains it well)

The essential line is always this one:
      Print |Content-Type:application/vnd.ms-excel|

If the next line:
      Print |Content-Disposition: Attachment; filename=»|+filename+|»|
is left out, the browser embeds an Excel-object all by itself to display the data you send. You can apply colours using CSS.

The users specified that they want it in Excel file. If I understand your suggestion, then I just send the HTML file?

What the users mean is that they want the file opened/presented in Excel. They’re not interested in how things work «under the hood»!
You can still name the html file «.xls», or add a header to the file so Windows will know what to do with it.
My users asked for Excel just as well. None ever complained and I never had to negotiate the installation of MS Office on a Domino server.

Anyway, you’ve managed to have Excel installed. That was the biggest reason to find an alternative. There’s no reason now have this discussion! ;-)

Now it is not working again and I did not change a thing since my last change.

:scratching my head:

I’ve requested that this question be closed as follows:

Accepted answer: 0 points for coronoahcoro’s comment #38194248

for the following reason:

Find solution from the external link

No sir, sorry, but you’re not playing fair, and I can’t accept that you close this question like that. You didn’t know why you got the Automation object error, and that’s what we explained you all about. That problem was solved. The discussion that followed should have been in one or more separate questions.

The original question is about an automation error.
In http:#a38194206 the asker confirms that Sjef’s suggestion helped in solving that issue.

Appearently, the asker got then stuck on secundary issues and may have managed to solve those without further help, but we’re all familiar with EE’s set of rules aren’t we?

I recommend accepting http:#a38192236.

Понравилась статья? Поделить с друзьями:
  • Excel create add in
  • Excel create a pie chart
  • Excel countries of the world
  • Excel counting rows in a range
  • Excel countifs with dates