Здравствуйте. |
|
Karataev Пользователь Сообщений: 2306 |
Наверное Вам надо создать пустой файл, скопируйте в него все листы из имеющегося файла, и скопируйте модули с макросами. С тем файлом, который Вы выложили на форуме, работать наверное нельзя, т.к. если зайти в VBE, то видно, что несколько модулей книг. Такого по идее не должно быть. |
Вот и хотелось причину выяснить. |
|
Karataev Пользователь Сообщений: 2306 |
Причину можно искать, но файлом в том виде, какой сейчас есть, мне кажется нельзя пользоваться. |
sokol92 Пользователь Сообщений: 4446 |
Уважаемый DmitriyBastr! Профессор ( ZVI ) уже наметил для Вашего файла (и аналогичных) курс лечения . |
DmitriyBastr Пользователь Сообщений: 82 |
#6 21.02.2018 15:00:35 Этим файлом и не пользуются уже. |
Разрушительный сбой |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
Есть программа , написанная на VBA и находится на сервере. Несколько человек одновременно работает с этими даннымы.
До сих пор это программа работала без проблема.
Но, сегодня мне понадобилось нескольо изменения делать и для этого и отключила доступ к книге.
После изменение хотела поставить галочку доступ к книге. После этого программа не открывается. Такая ошибка получается: «Automation error. Разрушительный сбой»
Дело в том что это ошибка получается только после галочку доступ к книге.
Что за ошибка? Что можно делать?
Только сейчас заметила что Office 2007 все нормально работает. А Office 2010 и 2013 такая ошибка получается.
может неустановлена библиотека
- Профессиональные приемы работы в Microsoft Excel
-
►
Обмен опытом -
►
Microsoft Excel -
►
Automation error. Разрушительный сбой
Return to VBA Code Examples
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.
Sub TestAutomation()
Dim strFile As String
Dim wb As Workbook
'open file and set workbook variable
strFile = Application.GetOpenFilename
Set wb = Workbooks.Open(strFile)
'Close the workbook
wb.Close
'try to activate the workbook
wb.Activate
End Sub
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:
Sub InsertPicture()
Dim i As Integer
Dim shp As Object
For i = 1 To 100
With Worksheets("Sheet1")
'set the object variable
Set shp = .OLEObjects.Add(ClassType:="Forms.Image.1", Link:=False, DisplayAsIcon:=False, Left:=.Cells(i, "A").Left, Top:=.Cells(i, "A").Top, Width:=264, Height:=124)
End With
With shp
.Object.PictureSizeMode = 3
'load the picture
.Object.Picture = LoadPicture("C:dataimage" & i & ".jpg")
.Object.BorderStyle = 0
.Object.BackStyle = 0
End With
Next i
End Sub
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.
Sub InsertPicture()
Dim i As Integer
Dim shp As Object
For i = 1 To 100
With Worksheets("Sheet1")
'set the object variable
Set shp = .OLEObjects.Add(ClassType:="Forms.Image.1", Link:=False, DisplayAsIcon:=False, Left:=.Cells(i, "A").Left, Top:=.Cells(i, "A").Top, Width:=264, Height:=124)
End With
With shp
.Object.PictureSizeMode = 3
'load the picture
.Object.Picture = LoadPicture("C:dataimage.jpg")
.Object.BorderStyle = 0
.Object.BackStyle = 0
End With
'clear the object variable
Set shp = Nothing
Next i
End Sub
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!
Learn More!
Ребята. И файлик у меня, благодаря более ранним советам бинарный, и наполнение формы уже практически на 98 % автоматизировано.
А вот перенести содержимое листов из одного файла в другой — практически невозможно. И дело даже не в объеме. Сами листы постоянно меняются.
Я просто научился жить с этой ошибкой. Возникает она строго когда меняется расположение/размер элемента на форме, которая
1. создана в 97 версии Excel
2. испытала по меньшей мере 48 модификаций (я версии считаю)
3. содержит пару сотен разных элементов.
4. испытала неоднократные нагрузки на основные элементы в тысячи и десятки тысяч записей
Я не говорю, что моя форма — великий и непогрешимый продукт моцга.
Она давно уже просится в отдельное приложение. Но пока я дорабатываю мелочи концепции — об отдельном приложении речи не идет.
То что xlsm — большая мусорка, я понимаю. Но сделать с этим пока ничего не могу. В файлах хls возникают проблемки с условным форматированием, некоторыми новыми функциями. От условного форматирования я планомерно ухожу. Но работы пока в этом направлении много. Индикация — важная вещь при экспресс-анализе непрерывно добавляющейся инфы.
А вот как уйти от функций СУММЕСЛИ, СЧЁТЕСЛИ и т.п.? Можно, конечно, наваять свою приблуду, но работать она будет заведомо и ощутимо медленнее. Доживу до SQL — буду выпендриваться.
Так что большинство советов я учитываю и использую. Они помогли мне в моем случае локализовать ошибку, условия ее возникновения, действия к ней приводящие, что мной и освещено здесь.
Добавлено через 2 часа 11 минут
Сообщение от StepInLik
6. На счет инфы со ссылкой и не лицензионным ПО не понял. Пожалуйста поясните.
Забыл совсем… прошу прощения. Если ПО нелицензионное (офис), то объективно возникает ошибка при подключении модуля, следящего за этим делом. Но у меня ошибка возникает и на лицензионном 2010 офисе (prof+). Так что ко мне это дело не относится. Ссылку здесь я привел, суммируя всё, что я нахожу или к чему прихожу сам по данному вопросу.
Добавлено через 5 минут
Сообщение от StepInLik
странно что он у вас вообще работает(и даже открывается) при (по всей видимости) таких объемах и будучи эксэмэльным (xlsx(m)
мои собственные проверки. Файл xlsm (2010-2013) работает и открывается при количестве строк 140 тыс. Файл еще работал, но у меня уже не открылся при количестве строки 730 тыс. Проблема была в нехватке оперативки. так что большой вопрос — а открылся ли файл. С таким монстром работать в excel почти невозможно (недопустимый износ нервов). поэтому дальше я не экспериментировал. Понятно, что мои задачи — задачи баз данных. Я сейчас отрабатываю концептуально программу обработки БД. Формировать БД и приложения, работающие с ней буду позже. И скорее всего с профильными спецами. Моя задача будет — грамотно формировать ТО с учетом ньюансов. Кто-б мне такой подарок в жизни сделал?!
Добавлено через 4 минуты
Сообщение от StepInLik
переносите не объекты (со всем мусором), а внешнее состояние объектов — т.е. содержимое, оформление, названия …
что имелось ввиду? копирование? как перенести форму? перерисовать?
я открываю VBA и драг-энд-дропом перетаскиваю формы, класс, модули из одного файла в другой. листы — копирую стандартным способом «переместить/копировать лист»
Добавлено через 1 минуту
Сообщение от anton-sf
с контролем создания и уничтожения объектов
я не уничтожаю и не создаю сами объекты на форме. Они созданы на этапе конструирования, позиционированы и отредактированы. Их наполнение — программное.
При редактировании элементов и возникает сбой.
Добавлено через 45 минут
Сообщение от AndreA SN
При редактировании элементов
имеется ввиду не программное наполнение, а редактирование элементов в конструкторе формы
One of the more frustrating errors to occur in VBA is the Automation Error. It can often pop up for no apparent reason despite your code looking perfect.
Reasons for This Error
There are a variety of reasons that this can occur.
Microsoft Office is made up of Objects – the Workbook object, Worksheet Object, Range object and Cell object to name just a few in Excel; and the Document Object in Word. Each object has multiple properties and methods that are able to be programmed to control how the object behaves. If you do not program these methods correctly, or do not set a property correctly, then an automation error can occur.
It can be highly annoying as the code will run perfectly for a while, and then suddenly you’ll see this!
You may get a number of different messages for this error.
The Object Has Disconnected from Its Client
An automation error could occur when you are referring to a workbook or worksheet via a variable, but the variable is no longer active. Make sure any object variables that you are referring to in your code are still valid when you call the property and methods that you are controlling them with.
Excel Error Load Form
An automation error could occur within Excel if you load a form while another object (like the worksheet or range object) are still referenced. Remember to set your object references to NOTHING after you have finished writing the code to control them with.
Error Hiding/Unhiding Sheets In Excel
There are 3 ways to control the visible property in an Excel sheet in VBA – xlSheetVisible
, xlSheetHidden
or xlSheetVeryHidden
. An automation error could occur if you are trying to write information to a sheet which has the xlVeryHidden
property set – make sure you set the sheet to visible in the code before you try to write anything to the sheet using Visual Basic Code.
Error 429 and 440
If you receive either of these errors, it can mean that your DLL files or ActiveX controls that you might be using are not correctly registered on your PC, or if you are using an API incorrectly. It can also occur if you are running using 32-bit files on a 64-bit machine, or vice versa.
Automation Error When Running Macro Enabled Workbook Over A Network
If you have a workbook open over a network, and you get an automation error when you run a macro, check your network connections – it could be that the network path is no longer valid. Check you network paths and connections and make sure that they are all still working.
ADODB Automation Error
This error can occur when you are programming within Microsoft Access and are using the ADODB.Connection object. It can be caused by any number of reasons from conflicting DLL files to a registry corruption, or simply that you did not set the recordlist object to nothing when you were finished using it!
Common Causes and Things to Check
Here are some reasons you might be getting the error. Perhaps you are…
- Trying to write information to hidden sheets or cells.
- Trying to write information to other documents or workbooks.
- Referring to objects that do not exist.
- Needing to install an update to Office, or the correct .Net framework.
- Loading objects (like pictures) into memory using a loop, and failing to clear the memory between each load (set Pic = Nothing).
- A Corrupt Registry – this is a hard one, as it often means that you need to remove Office entirely from your machine and then re-install it.
Ways to Solve It
Error Trapping
Error trapping is one of the best ways to solve this problem. You can use On Error Resume Next – or On Error GoTo Label – depending on your needs at the time. If you want the code to carry on running and ignore the error, use On Error Resume Next. If you want the code to stop running, create an error label and direct the code to that error label by using On Error GoTo
label
.
Clear the Memory
Another way to solve the problem is to make sure you clear any referred objects either in a loop or at the end of your code. For example, if you have referred to a picture object, set the picture object to NOTHING, or if you have referred to a Worksheet object, set the Worksheet object to NOTHING once you have run the code for that picture of worksheet.
The code example below will insert a picture into a worksheet. It may or may not give you an automation error!
Sub InsertPicture() Dim i As Integer For i = 1 To 100 With Worksheets("Sheet1") Set shp = .OLEObjects.Add(ClassType:="Forms.Image.1", _ Link:=False, DisplayAsIcon:=False, Left:=.Cells(i, "A").Left , Top:=.Cells(i, "A").Top, Width:=264, Height:=124) End With With shp .Object.PictureSizeMode = 3 .Object.Picture = LoadPicture("C:dataimage" & i & ".jpg") .Object.BorderStyle = 0 .Object.BackStyle = 0 End With Next i End Sub
The variable is declared as an OLEObject, 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 – some formatting taking place at the same time. I have then added 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 error often occurs when Excel runs out of memory – assigning an object over and over again without clearing the object could mean that Excel is struggling with memory and could lead to an automation error.
We can solve this problem 2 ways:
- Set the object to NOTHING after it is inserted each time
- Add an error trap to the code.
Sub InsertPicture() On Error Resume Next Dim i As Integer For i = 1 To 100 With Worksheets("Sheet1") Set shp = .OLEObjects.Add(ClassType:="Forms.Image.1", _ Link:=False, DisplayAsIcon:=False, Left:=.Cells(i, "A").Left , Top:=.Cells(i, "A").Top, Width:=264, Height:=124) End With With shp .Object.PictureSizeMode = 3 .Object.Picture = LoadPicture("C:dataimage" & i & ".jpg") .Object.BorderStyle = 0 .Object.BackStyle = 0 End With Set shp = Nothing Next i End Sub
Make sure your PC is up to date
A third way to solve the problem is to install the required update to Office or Windows, or the latest version of the .Net framework. You can check to see if there are any updates available for your PC in your ‘Check for updates’ setting on your PC.
In Windows 10, you can type ‘updates’ in the search bar, and it will enable you to click on “Check for updates“.
It is always a good idea to keep your machine up to date.
Run a Registry Check
If all else fails, there are external software programs that you can download to run a check on the registry of your PC.
As you can see from above, this error often has a mind of its own – and can be very frustrating to solve. A lot of the times trial and error is required, however, writing clean code with good error traps and referring to methods, properties and objects correctly often can solve the problem.
- Remove From My Forums
-
Вопрос
-
Hello,
I found a VBA bug, after Excel 2016 update to latest version. Checked on 2007/2010/2013 Excel — this works fine.
Can someone confirm it’s not only me have this problem, and how this can be solved?
Open Excel, write something in B5 cell.
In VBA write 3 lines:
Sub ine() ActiveSheet.PrintPreview End Sub
Then press RUN. It will open PrintPreview page of your Excel document. Then press button «Show Margins», and try to move margin on paper. You should encounter VBA Automation error.
Adding screenshot: (Body text cannot contain images or links until we are able to verify your account.) I will add later
And after Excel crashes. From windows logs got this:
Faulting application name: EXCEL.EXE, version: 16.0.7369.2038, time stamp: 0x57f8d67c
Faulting module name: EXCEL.EXE, version: 16.0.7369.2038, time stamp: 0x57f8d67c
Exception code: 0xc0000005
Fault offset: 0x0005bca2
Faulting process id: 0x1d64
Faulting application start time: 0x01d22851752c0b21
Faulting application path: C:Program Files (x86)Microsoft OfficeRootOffice16EXCEL.EXE
Faulting module path: C:Program Files (x86)Microsoft OfficeRootOffice16EXCEL.EXE
Report Id: 1234cd8a-9448-11e6-9c35-74867a53b6c5
Faulting package full name:
Faulting package-relative application ID:
Ответы
-
-
Предложено в качестве ответа
26 октября 2016 г. 6:23
-
Помечено в качестве ответа
JuliusAST
27 октября 2016 г. 11:42
-
Предложено в качестве ответа
-
Hi,
You can also give a feedback via User Voice forum:
https://excel.uservoice.com/forums/304921-excel-for-windows-desktop-application
This forum is a way MS collect feedback from users.
Hope it’s helpful.
Regards,
Emi Zhang
TechNet Community SupportPlease remember to mark the replies as answers if they help and
unmark them if they provide no help.
If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.I did, can you give 3 votes?: https://excel.uservoice.com/forums/304921-excel-for-windows-desktop-application/suggestions/16722592-vba-activesheet-printpreview-automation-error-16-0
-
Предложено в качестве ответа
Emi ZhangMicrosoft contingent staff
26 октября 2016 г. 6:23 -
Помечено в качестве ответа
Emi ZhangMicrosoft contingent staff
28 октября 2016 г. 1:00
-
Предложено в качестве ответа