Ошибка automation error excel

Всем привет. Кто сталкивался подскажите, как можно отловить эту ошибку. Часто встречается в офисе но не у всех. Там есть, там нет. Макросы работают одни и те же. Причем ошибка появляется без каких-либо пояснений и предложений к отладке.
 

Laider

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

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

Всем привет. Кто сталкивался подскажите, как можно отловить эту ошибку. Часто встречается в офисе но не у всех. Там есть, там нет. Макросы работают одни и те же. Причем ошибка появляется без каких-либо пояснений и предложений к отладке.

 

Alemox

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

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

Проблему надо искать в макросе, а не в компьютере. Если у вас макрос работает с несколькими книгами, то возможно, что он теряет фокус нужной книги. Сам несколько раз сталкивался с таким. Неправильно прописан код. Например вместо ActiweWorkbook нужно было использовать Thisworkbook и прочее. Если явно не прописаны какие-то имена листов и книг. Или если название макроса совпадает с названием макроса в другой книге. Но ошибку надо искать именно в макросах. Может макрос на открытие книги чего не так делает. Думаю, что теряется макрос при выполнении кода.

Мастерство программиста не в том, чтобы писать программы, работающие без ошибок.
А в том, чтобы писать программы, работающие при любом количестве ошибок.

 

Laider

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

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

Сегодня нашел проблему в одном из таких. Сборщик из нескольких книг. Заменил копирование диапазонов выделением, на указание конкретных его границ. Проблема исчезла. Знал бы сразу, сразу бы так и писал код. Очень странно что на одном ПК все работает, а на другом нет. Теперь надо проверять все старые схожие макросы где использовал Selection.

 

Dima S

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

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

Для сбора из нескольких книг использовать Select вообще не обязательно (даже нежелательно, ибо тормозит).
Поищите тут на сайте полно реализаций сбора данных из нескольких книг.

 

Karataev

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

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

#5

24.03.2018 10:51:42

Laider, мне кажется, что Вы неправильно назвали тему. Вы хотите не отловить, а понять причину ошибки.
А вообще, чтобы отловить ошибку, нужно использовать код ниже. Хотя припоминаю, что для каких-то ошибок это не работает (не могу сейчас вспомнить).

Скрытый текст

Изменено: Karataev24.03.2018 10:52:51

Содержание

  1. VBA Automation Error
  2. Referring to a Variable no Longer Active
  3. Memory Overload
  4. DLL Errors and Updating Windows
  5. VBA Coding Made Easy
  6. VBA Code Examples Add-in
  7. Excel automation fails second time code runs
  8. Symptoms
  9. Cause
  10. Resolution
  11. Status
  12. More Information
  13. Steps to reproduce the behavior
  14. References
  15. Vba automation error что это
  16. Excel automation fails second time code runs
  17. Symptoms
  18. Cause
  19. Resolution
  20. Status
  21. More Information
  22. Steps to reproduce the behavior
  23. References
  24. Vba automation error что это

VBA Automation Error

In this Article

This tutorial will explain what a VBA Automation Error means and how it occurs.

Excel is made up of objects – the Workbook object, Worksheet object, Range object and Cell object to name but a few. Each object has multiple properties and methods whose behavior can be controlled with VBA code. If the VBA code is not correctly programmed, then an automation error can occur. It is one of the more frustrating errors in VBA as it can often pop up for no apparent reason when your code looks perfectly fine!

(See our Error Handling Guide for more information about VBA Errors)

Referring to a Variable no Longer Active

An Automation Error could occur when you are referring to a workbook or worksheet via a variable, but the variable is no longer active.

When we run the code above, we will get an automation error. This is due to the fact that we have opened a workbook and assigned a variable to that workbook. We have then closed the workbook but in the next line of code we try to activate the closed workbook. This will cause the error as the variable is no longer active.

If we want to activate a workbook, we first need to have the workbook open!

Memory Overload

This error can also sometimes occur if you have a loop and you forget to clear an object during the course of the loop. However, it might only occur sometimes, and not others- which is one of the reasons why this error is can be so annoying.

Take for example this code below:

The variable is declared as an Object, and then the SET keyword is used to assign an image to the object. The object is then populated with an image and inserted into the Excel sheet with some formatting taking place at the same time. We then add a loop to the code to insert 100 images into the Excel sheet. Occasionally this causes an automation error, but sometimes it doesn’t – frustrating, right?

The solution to this problem is to clear the object variable within the loop by setting the object to NOTHING – this will free the memory and prevent the error.

DLL Errors and Updating Windows

Sometimes the error occurs and there is nothing that can be done within VBA code. Re-registering DLL’s that are being used, making sure that our Windows is up to date and as a last resort, running a Registry Check as sometimes the only things that may work to clear this error.

A good way of avoiding this error is to make sure that error traps are in place using the On Error Go To or On Error Resume Next routines.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Источник

Excel automation fails second time code runs

Symptoms

While running code that uses Automation to control Microsoft Excel, one of the following errors may occur:

In Microsoft Excel 97 and in later versions of Excel, you receive one of the following error message:

Error message 1

Run-time error ‘1004’:
Method ‘ ‘ of object ‘_Global’ failed

Error message 2

Application-defined or object-defined error

In Microsoft Excel 95, you receive one of the following error messages:

Error message 1

Run-time error ‘-2147023174’
OLE Automation error

Error message 2

Run-time error ‘462’:
The remote server machine does not exist or is unavailable.

Cause

Visual Basic has established a reference to Excel because of a line of code that calls an Excel object, method, or property without qualifying the element with an Excel object variable. Visual Basic does not release this reference until you end the program. This errant reference interferes with automation code when the code is run more than one time.

Resolution

To resolve this problem, modify the code so each call to an Excel object, method, or property is qualified with the appropriate object variable.

Status

This behavior is by design.

More Information

To automate Microsoft Excel, you establish an object variable that usually refers to the Excel Application object or the Excel Workbook object. Other object variables can then be set to refer to a Worksheet, a Range, or other objects in the Microsoft Excel object model. When you write code to use an Excel object, method, or property, you should always precede the call with the appropriate object variable. If you do not, Visual Basic establishes its own reference to Excel. This reference might cause problems when you try to run the automation code multiple times. Note that even if the line of code begins with the object variable, a call may be made to an Excel object, method, or property in the middle of the line of code that is not preceded with an object variable.

The following steps illustrate how to reproduce this issue and how to correct the issue.

Steps to reproduce the behavior

Start a new Standard EXE project in Visual Basic. Form1 is created by default.

On the Project menu, click References, and then check the Object Library for the version of Excel that you intend to automate.

Place a CommandButton control on Form1.

Copy the following code example to the Code Window of Form1.

On the Run menu, click Start, or press F5 to start the program.

Click the CommandButton control. No error occurs. However, a reference to Excel has been created and has not been released.

Click the CommandButton control again. Notice that you receive one of the error messages that are discussed in the «Symptoms» section.

Note The error message occurs because the code refers to the method of the cell without preceding the call with the
xlSheet object variable.

Stop the project and change the following line of code:

Change the line of code to resemble the following line of code.

Run the program again. Notice that you can run the code multiple times without receiving an error message.

References

For more information, click the following article numbers to view the articles in the Microsoft Knowledge Base:

167223 Microsoft Office 97 Automation Help file available

189618 You may receive the «Run-time error ‘-2147023174’ (800706ba)» error message or the «Run-time error ‘462’» when you run Visual Basic code that uses Automation to control Word

Источник

Vba automation error что это

Вроде как на ровном месте (т.е. до сегодня пару лет работало) вот такая строчка кода:

Set fs = CreateObject(«Scripting.FileSystemObject»)

стала вызывать вот такую ошибку:

Run-time error ‘-2147024770 (8007007e)’:
Automation error

Собственно, это использовалось для последующей проверки ссуществования файла (FileExists). И вот.
Подскажите, пожалуйста, что тут может быть? Библиотеки слетели? Куда смотреть?

Originally posted by rtttv
[b]Собственно, это использовалось для последующей проверки ссуществования файла (FileExists). И вот…

Так всегда происходит , когда люди пренебрегают родными функциями и используются посторонние библиотеки.

Посмотрите, есть ли ссылки на библиотеки Microsoft Scripting Runtime

Спасибо. Именно это — Microsoft Scripting Runtime! Сбилась (в системе) регистрация библиотеки scrrun.dll. А в Excel (Tools — References) «галка» на неё и не стояла. И сейчас не стоит, но всё работает!Т.е. системные библиотеки сами подтягиваются? А вообще в такой ситуации нужно устанавливать reference?

Так всегда происходит , когда люди пренебрегают родными функциями и используются посторонние библиотеки.

Originally posted by rtttv
[b]А в Excel (Tools — References) «галка» на неё и не стояла. И сейчас не стоит, но всё работает

Это кстати, позволяет избежать проблем, связанных с различными версиями (при передаче файла другим лицам)

что Naeel Maqsudov предлагал . Application.Run

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

Источник

Excel automation fails second time code runs

Symptoms

While running code that uses Automation to control Microsoft Excel, one of the following errors may occur:

In Microsoft Excel 97 and in later versions of Excel, you receive one of the following error message:

Error message 1

Run-time error ‘1004’:
Method ‘ ‘ of object ‘_Global’ failed

Error message 2

Application-defined or object-defined error

In Microsoft Excel 95, you receive one of the following error messages:

Error message 1

Run-time error ‘-2147023174’
OLE Automation error

Error message 2

Run-time error ‘462’:
The remote server machine does not exist or is unavailable.

Cause

Visual Basic has established a reference to Excel because of a line of code that calls an Excel object, method, or property without qualifying the element with an Excel object variable. Visual Basic does not release this reference until you end the program. This errant reference interferes with automation code when the code is run more than one time.

Resolution

To resolve this problem, modify the code so each call to an Excel object, method, or property is qualified with the appropriate object variable.

Status

This behavior is by design.

More Information

To automate Microsoft Excel, you establish an object variable that usually refers to the Excel Application object or the Excel Workbook object. Other object variables can then be set to refer to a Worksheet, a Range, or other objects in the Microsoft Excel object model. When you write code to use an Excel object, method, or property, you should always precede the call with the appropriate object variable. If you do not, Visual Basic establishes its own reference to Excel. This reference might cause problems when you try to run the automation code multiple times. Note that even if the line of code begins with the object variable, a call may be made to an Excel object, method, or property in the middle of the line of code that is not preceded with an object variable.

The following steps illustrate how to reproduce this issue and how to correct the issue.

Steps to reproduce the behavior

Start a new Standard EXE project in Visual Basic. Form1 is created by default.

On the Project menu, click References, and then check the Object Library for the version of Excel that you intend to automate.

Place a CommandButton control on Form1.

Copy the following code example to the Code Window of Form1.

On the Run menu, click Start, or press F5 to start the program.

Click the CommandButton control. No error occurs. However, a reference to Excel has been created and has not been released.

Click the CommandButton control again. Notice that you receive one of the error messages that are discussed in the «Symptoms» section.

Note The error message occurs because the code refers to the method of the cell without preceding the call with the
xlSheet object variable.

Stop the project and change the following line of code:

Change the line of code to resemble the following line of code.

Run the program again. Notice that you can run the code multiple times without receiving an error message.

References

For more information, click the following article numbers to view the articles in the Microsoft Knowledge Base:

167223 Microsoft Office 97 Automation Help file available

189618 You may receive the «Run-time error ‘-2147023174’ (800706ba)» error message or the «Run-time error ‘462’» when you run Visual Basic code that uses Automation to control Word

Источник

Vba automation error что это

прошу помочь!
Выскочила такая «бяка» при запуске ранее рабочего макроса. Подозреваю, что что-то с настройками самого Ёкселя (либо ВБА), поскольку эксельный файл с этим макросом даже не хочет сохраняться («Документ не сохранен»). Хотя файлы с другими макросами вполне работоспособны. Офис-2003, в настройке безопасности доверялки подключены.

зы. Сколько уж зарекался оставлять свой комп коллегам

Automation error (Error 440)

When you access Automation objects, specific types of errors can occur. This error has the following cause and solution:

An error occurred while executing a method or getting or setting a property of an object variable. The error was reported by the application that created the object.
Check the properties of the Err object to determine the source and nature of the error. Also try using the On Error Resume Next statement immediately before the accessing statement, and then check for errors immediately following the accessing statement.

ошибка при установке (получении) свойств обьекта.
рекомендуют использовать On Error Resume Next чтобы в свойствах Err получить более детальную информации о произошедшем.

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

Источник

‎Nov 11 2019

04:42 AM

This is usually an indication the VBA project has become corrupted. One example of when this sometimes happens is if you are debugging a VBA project which contains User Defined Functions called from cells. If you save the file while in debug mode this sometimes happens in my experience. There might be several ways to get out of this state, one being exporting all VBA modules, then saving as xlsx file, closing and re-opening the xlsx, importing the VBA modules and then saving as xlsm.

‎Nov 11 2019

04:53 AM

@Jan Karel Pieterse 

Thanks Jan. That is probably what happened — yes, I was debugging and maybe save before the process was complete. To clarify, after exporting and saving as XLSX, do I need to remove the old modules or just import over them? Also, would saving in Safe Mode automatically do the same thing, or similar, by editing the corrupted code?

‎Nov 11 2019

05:24 AM

If you FIRST close the newly saved xlsx and then reopen it, all VBA will have been removed from it (INCLUDING code in sheet modules and in ThisWorkbook, so you may want to check those too before closing the xlsx!).

Saving in safe mode is no different from saving in «normal» mode.

‎Nov 11 2019

05:47 AM

@Jan Karel Pieterse 

Ah, the modules are gone after saving as xlsx. I see. And they have now been re-imported.

Also re-imported forms. These exported from other version in two types, FRM and FRX. Will investigate these, but they imported successfully. Thank you for the instructions. I should be okay from here.

‎Nov 11 2019

07:03 AM

You may benefit from using Code Cleaner by Rob Bovey.

‎Nov 11 2019

04:42 AM

This is usually an indication the VBA project has become corrupted. One example of when this sometimes happens is if you are debugging a VBA project which contains User Defined Functions called from cells. If you save the file while in debug mode this sometimes happens in my experience. There might be several ways to get out of this state, one being exporting all VBA modules, then saving as xlsx file, closing and re-opening the xlsx, importing the VBA modules and then saving as xlsm.

‎Nov 11 2019

04:53 AM

@Jan Karel Pieterse 

Thanks Jan. That is probably what happened — yes, I was debugging and maybe save before the process was complete. To clarify, after exporting and saving as XLSX, do I need to remove the old modules or just import over them? Also, would saving in Safe Mode automatically do the same thing, or similar, by editing the corrupted code?

‎Nov 11 2019

05:24 AM

If you FIRST close the newly saved xlsx and then reopen it, all VBA will have been removed from it (INCLUDING code in sheet modules and in ThisWorkbook, so you may want to check those too before closing the xlsx!).

Saving in safe mode is no different from saving in «normal» mode.

‎Nov 11 2019

05:47 AM

@Jan Karel Pieterse 

Ah, the modules are gone after saving as xlsx. I see. And they have now been re-imported.

Also re-imported forms. These exported from other version in two types, FRM and FRX. Will investigate these, but they imported successfully. Thank you for the instructions. I should be okay from here.

‎Nov 11 2019

07:03 AM

You may benefit from using Code Cleaner by Rob Bovey.

Понравилась статья? Поделить с друзьями:
  • Ошибка b1346 chevrolet epica
  • Ошибка b1150 lexus rx330
  • Ошибка automatic gear fault пежо 307
  • Ошибка b1024 nissan жук
  • Ошибка b1325 опель инсигния