Runtime error 5460 ошибка файла vba excel

For a customer, I have created a Global template with a ’New Document” button that shows a userform letting the user create a new document from a choice of templates, e.g. Letter, Invoice, etc.
Recently, we have added the choice Report.

The code executed from this userform is very simple, using e.g.

Documents.Add Template:="Letter.dotm", NewTemplate:=False

to create the new documents.

The Report template is – by my standards – quite complex, with AutoNew and AutoClose macros, an EventClassModule, it writes to and reads from the CustomDocumentProperties, opens several specific Word documents from where it copies text and pastes it into the Report document, etc.

The first time a new Report is created it works as planned; but the second time (in the same Word session) the Report option is used, a ‘Runtime Error 5460’ occurs. And after that, any of the other document options returns the same error.

Quitting Word and starting a new Word session sets everything back to normal, until the Report template again is called the second time.

Strangely enough, the Report template works with no errors when new documents based on it are created directly from Explorer, as many times in the same Word session as needed.

The problem occurs in Word 2016 (365) with Windows 7 Pro, but not in Word 2013 with Windows 10.

Anybody that has ever experienced anything like this?? Help is really appreciated.


Runtime Error 5460: ‘A file error has occured.’

Debug is not possible.

The Report template has thousands of lines of code and I have not been able to find out if it is in fact code in the Report template that causes the error, or code in the Global template.

As said, the Report template works fine when used from Explorer, and when called via the Global template in 2013 everything works there too.


Problem solved!
I followed the advice from @macropod and added the path also.
In stead of just using

'…
If OptionButton3.Value = True Then
    Documents.Add Template:="Report.dot", NewTemplate:=False
End If
'…

I changed the code to:

Private Sub CommandButton1_Click()

Dim strPath As String
strPath = Options.DefaultFilePath(wdWorkgroupTemplatesPath)

Dim wdApp As Word.Application
Set wdApp = GetObject(, "Word.Application")

'…
If OptionButton3.Value = True Then
    wdApp.Documents.Add Template:=strPath & "Report.dot", NewTemplate:=False
End If
'…

End Sub

Thanks!!

Для клиента я создал кнопку «Глобальный шаблон с новым документом», в которой отображается пользовательская форма, позволяющая пользователю создать новый документ с помощью выбора шаблонов, например, «Письмо», «Счет-фактура» и т.д. Недавно мы добавили отчет «Выбор».

Код, выполненный из этой пользовательской формы, очень прост, используя, например,

Documents.Add Template:="Letter.dotm", NewTemplate:=False

для создания новых документов.

Шаблон отчета — по моим стандартам — довольно сложный, с макросами AutoNew и AutoClose, EventClassModule, он записывает и считывает из CustomDocumentProperties, открывает несколько документов Word, где он копирует текст и вставляет его в документ отчета и т.д.

В первый раз, когда создается новый отчет, он работает так, как планировалось; но во второй раз (в том же сеансе Word) используется параметр «Отчет», появляется «Ошибка выполнения 5460». И после этого любой из других параметров документа возвращает ту же ошибку.

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

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

Проблема возникает в Word 2016 (365) с Windows 7 Pro, но не в Word 2013 с Windows 10.

Кто-нибудь, кто когда-либо испытывал подобное? Помощь очень ценится.

Ошибка выполнения 5460: «Произошла ошибка файла».

Отладка невозможна.

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

Как сказано, шаблон отчета отлично работает при использовании в проводнике, а при вызове через глобальный шаблон в 2013 году все работает.

Задача решена! Я последовал совету @macropod и добавил путь. Вместо того, чтобы просто использовать

'…
If OptionButton3.Value = True Then
Documents.Add Template:="Report.dot", NewTemplate:=False
End If
'…

Я изменил код на:

Private Sub CommandButton1_Click()

Dim strPath As String
strPath = Options.DefaultFilePath(wdWorkgroupTemplatesPath)

Dim wdApp As Word.Application
Set wdApp = GetObject(, "Word.Application")

'…
If OptionButton3.Value = True Then
wdApp.Documents.Add Template:=strPath & "Report.dot", NewTemplate:=False
End If
'…

End Sub

Спасибо!!

 

paylevan

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

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

Коллеги, здравствуйте.

В процессе автономной работы Excel-приложения периодически возникают ошибки вида «Run-time error» (пример во вложенной фотографии) — из-за этого останавливается выполнение макросов и всего файла в целом. После нажатия кнопки «End» на всплывающем окне всё нормализуется до следующего появления подобной ошибки.

Прошу вас, по возможности, уточнить: можно ли как-то прописать в макросах, VBA-коде книги или листов универсальную команду, чтобы при появлении подобных и любых других ошибок они автоматически обрабатывались и работа Excel не прекращалась?

Изменено: paylevan23.11.2013 16:44:22

 

Юрий М

Модератор

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

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

Вы фотографируете экран? )

 

paylevan

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

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

Нет, обычно пользуюсь PrtSc. Просто в этот раз надо было на телефон сфотографировать, чтобы взять с собой. Буду признателен за конструктивный совет.

 

ikki

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

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

#4

23.11.2013 16:48:41

on error goto
on error resume next
и т.д.

Цитата
при появлении подобных и любых других ошибок они автоматически обрабатывались

а вот это как раз и надо будет прописать — как именно их обрабатывать.
ибо просто пропускать (как это делаете вы сейчас) — не всегда приведет к «всё нормализуется».

фрилансер Excel, VBA — контакты в профиле
«Совершенствоваться не обязательно. Выживание — дело добровольное.» Э.Деминг

 

ikki

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

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

пс. я таки не удивляюсь, почему объявления типа «лечу по фотографии» пользуются спросом :)

фрилансер Excel, VBA — контакты в профиле
«Совершенствоваться не обязательно. Выживание — дело добровольное.» Э.Деминг

 

paylevan

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

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

ikki

, везде «принтскрины» и «ножницы», а здесь фотография. Пусть будет  :)  . Для разнообразия  :)  .

Изменено: paylevan23.11.2013 17:02:39

 

The_Prist

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

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

Профессиональная разработка приложений для MS Office

Сама ошибка означает отсутствие у Вас доступа. К чему — Вам виднее. И простое игнорирование ошибки может в дальнейшем еще аукнуться. Поэтому надо точно знать, что именно этого хочется.

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

paylevan

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

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

#8

23.11.2013 17:36:57

The_Prist

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

ikki

, проставить в макросах следующие строки:
в начале

Код
On Error Resume Next

в конце

Код
On Error GoTo 0

Простейший пример решения данной проблемы — во вложенной фотографии. Если есть более надёжный вариант, прошу написать.

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

  • Error_Handling_VBA.PNG (28.97 КБ)

Изменено: paylevan23.11.2013 18:51:05

 

KuklP

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

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

E-mail и реквизиты в профиле.

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

Я сам — дурнее всякого примера! …

 

Юрий М

Модератор

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

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

#10

23.11.2013 17:42:49

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

Сомневаюсь: не должны два макроса одновременно запуститься.

 

KuklP

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

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

E-mail и реквизиты в профиле.

«Юрий М:
не должны два макроса одновременно запуститься.»
Разве что с разных машин. Тогда есть смысл добавить проверку на занятость файла. Но мы опять гадаем. :)

Я сам — дурнее всякого примера! …

 

ikki

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

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

#12

23.11.2013 17:56:17

Цитата
согласно совету ikki

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

например, для случая «одновременного» обращения к занятому файлу можно поставить небольшой цикл с оговоренным временем повторных попыток чтения, результат — опять же обрабатывать и, к примеру, если за ранее определенный промежуток времени файл открыть не удвлось — честно предупреждать пользователя и завершать работу.
а у вас не пойми что получается — попробовали прочитать файл — он занят — ну и фиг с ним — проигнорировали ошибку и пошли дальше, как будто всё нормально.

чего-то многовато я понаписал…
и ведь всё — очевидные вещи ;)

фрилансер Excel, VBA — контакты в профиле
«Совершенствоваться не обязательно. Выживание — дело добровольное.» Э.Деминг

 

paylevan

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

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

#13

23.11.2013 18:19:53

ikki

, кстати, именно цикл с временем и помог. Как раз так я и идентифицировал проблему с доступом.
В этой фразе «согласно совету ikki» имелось в виду «порекомендовал нужные функции»  :)   .
Именно для того, чтобы исключить проиллюстрированный Вами случай

Цитата
попробовали прочитать файл — он занят — ну и фиг с ним — проигнорировали ошибку и пошли дальше, как будто всё нормально.

и используется в конце строчка

Код
On Error GoTo 0

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

Изменено: paylevan23.11.2013 18:34:45

 

ikki

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

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

on error goto 0 используется не для перезапуска макроса, а для отключения обработки ошибок.
читайте справку ;)

фрилансер Excel, VBA — контакты в профиле
«Совершенствоваться не обязательно. Выживание — дело добровольное.» Э.Деминг

 

paylevan

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

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

#15

23.11.2013 18:36:09

Цитата
читайте справку

ikki

, именно с неё я и начал. И всегда рекомендую всем это делать.
Если у Вас есть более корректное, чем приведённое выше, решение обработки некритических ошибок в макросах, требующее лишь их перезапуска, прошу привести пример.
Возможно, нижняя строчка «On Error GoTo 0» необязательна и достаточно лишь добавить верхнюю «On Error Resume Next»?

Изменено: paylevan23.11.2013 18:50:11

 

ikki

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

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

обычно советуют поступать примерно так:
перед участком кода, могущем вызвать ошибку указанного вами типа, пишем:

on error resume next
‘ далее — код (как правило — один оператор/функция
if err>0 then exit sub ‘ ошибка таки произошла. выходим из процедуры
on error goto 0 ‘ в общем случае — необязательно, обычно нужно в процессе отладки. особенно если в вашем коде могут быть совсем другие ошибки. а без отключенного обработчика — они все будут игнорироваться и вы ничего толком не сможете проверить.

фрилансер Excel, VBA — контакты в профиле
«Совершенствоваться не обязательно. Выживание — дело добровольное.» Э.Деминг

 

paylevan

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

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

ikki

, спасибо большое за подробный ответ.

По поводу «on error goto 0» Вы правы: обратил внимание, что без этой строчки результат один и тот же.

Изменено: paylevan23.11.2013 18:51:10

 

Слэн

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

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

#18

29.11.2013 13:57:15

paylevan, наиболее точной и простой симуляцией вашего случая будет:
в начале

Код
on error goto er

и в конце программы:

Код
..
exit sub
er: end
endsub

 

ps вышеупомянутый код не получается выделить тегами..

Изменено: Слэн29.11.2013 14:24:56

Живи и дай жить..

 

Юрий М

Модератор

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

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

 

paylevan

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

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

#20

30.11.2013 13:15:35

Здравствуйте,

Слэн

, спасибо большое за предложенный вариант.

Внимание, откроется в новом окне.
PDFПечать

Проблема характерна для старших версий MS Office (2010 и выше).

При создании документов (протоколов или сводных отчетов) возможно возникновение ошибки «5981 — Не удается открыть банк макросов», как показано на рисунке.

Дополнительно данная ошибка может сопровождаться еще одной ошибкой (Error «5460 — Ошибка файла»), которая также возникает при создании новых документов.

Причиной данных ошибок является блокировка шаблонов программы из-за особого режима безопасности MS Word (блокируются файлы, полученные  из Internet, из внешнего источника или из сетевой папки).

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

Можно применить изменения к конкретному шаблону, используя кнопки «Разрешить редактирование» или «Включить содержимое», но лучше это сделать для всех используемых шаблонов, как описано ниже.

Известны 2 случая, которые приводят к блокировкам со стороны MS Word.

1 Случай. Блокируются шаблоны из стандартной папки templates другого ПК и воспринимаются MS Word как файлы из внешнего источника.

В данной ситуации необходимо добавить папку с шаблонами в надежные расположения MS Word через меню «Файл — Параметры», как показано на рисунке.

Путь к папке с шаблонами по умолчанию: C:ProgramDataattest55.1templates

Папка с шаблонами по умолчанию находится в папке с настройками пользователя. Где хранятся настройки пользователя дополнительно можно ознакомиться в следующем МАТЕРИАЛЕ.

2 Случай. Для шаблонов настроена отдельная папка templates.

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

Four ways to fix runtime error 1004 in Excel:

Workable Solutions Step-by-step Troubleshooting
Fix 1. Delete the GWXL97.XLA Files Fix the Excel error 1004 is to find and delete the error file. Go to C:Program FilesMS OfficeOfficeXLSTART…Full steps
Fix 2. Check the Trust Access to the VBA Project Object Model Enable a VBA project trust option in Excel Trust Center to fix Excel error 1004. Open a blank Excel file…Full steps
Fix 3. Create Another Excel Template Start a new Excel workbook and make sure there is only one worksheet in it. Format the workbook first…Full steps
Fix 4. Repair Corrupted Excel File Repair corrupted Excel files with a file recovery tool. EaseUS file repair tool fixes severely corrupted XLS and XLSX files and retrieves everything from Excel…Full steps

Microsoft Visual Basic for Applications (VBA) is developed to help users write programs for the Windows operating system. It runs as an internal programming language in Microsoft Office, such as Word, Excel, and PowerPoint.

Some users have reported that when running VBA in an Excel chart or trying to generate a Macro in Excel documents, an error message popped up saying: Runtime error 1004. And then they find themselves cannot access the Excel files. If you have the same encounter as these users, this post is the right place for you. You can find both the reasons and the corresponding solutions of this error code on this page.

How to Fix Excel Error 104

Runtime Error Details

The error message contains more information than the error code 1004. Generally, follow the error code, you can see a brief description. The most repeated error messages are listed below:

  1. Runtime error 1004: Application or object-defined error.
  2. Runtime error 1004: Method Ranger of Object Worksheet failed.
  3. Runtime error 1004: Copy Method of Worksheet Class failed.

The Reason Why You See Runtime Error 1004 in Excel

If you want to know how to fix runtime error 1004 in Excel properly, you need to understand what leads to this issue. The following are the most prominent reasons.

  • Macro Name Error

The Macro you are running is copying the original worksheet to a workbook with a defined name that you did not save and close before running the Macro.

  • File Conflict

When opening the VBA Excel file, it gets conflicted with other programs.

  • Too Many Legend Entries

The Excel chart contains more legend entries than space available to display the legend entries on the chart.

  • Excel File Corruption

Your .xls files got corrupted, infected, or damaged.

Although many reasons would cause this Excel error 1004 problem, luckily, some valid methods can help users re-access the files. Let’s check them one by one.

Fix 1. Delete the GWXL97.XLA Files to Fix Runtime Error 1004 in Excel

The easiest method to fix the Excel error 1004 is to find and delete the error file.

Step 1. Go to C:Program FilesMS OfficeOfficeXLSTART.

Step 2. Find GWXL97.XLA file and delete it.

Step 3. Reopen your Excel file and check if the problem is solved.

Fix 2. Check the Trust Access to the VBA Project Object Model

Another solution you can try is to enable a VBA project trust option in Excel Trust Center. Follow the detailed steps and have a try.

Step 1. Open a blank Excel file and click «Files» on the upper left.

Step 2. Click Option and go to Trust Center.

Enter Excel Option

Step 3. Find and enter the Trust Center Settings.

Enter Trust Center Settings

Step 4. Under Macro Settings, tick the option of «Trust access to the VBA project object model.»

Trust Access to the VBA Project

Now you can check your Excel file.

Fix 3. Create Another Excel Template to Fix Runtime Error 1004 in Excel

This method could be a little bit complicated, but it’s useful and worth trying.

Step 1. Please start a new Excel workbook and make sure there is only one worksheet in it.

Step 2. Format the workbook first and then put the data you need onto it.

Step 3. Tap File > Save As, first enter the file name, and click the unfold arrow in Save as Type column.

Excel Save As

Excel 2003: Choose Excel 97-2003 Template.

Excel 2007 or Later: Choose Excel Template.

Choose the Right Template

Step 4. Click «Save» to confirm.

Now you can insert it programmatically by using the following code: Add Type:=pathfilename. The file name is the one you set when you create the new Excel template.

Fix 4. Repair Corrupted Excel Files Due to Error 1004 

If all the above solutions can’t help you out, then there is one possibility that the Excel file you want to open is damaged. To fix a damaged Excel file, you can rely on file repair software. EaseUS Data Recovery Wizard is a great choice.

With this tool, click the «Repair» button and wait for it to fix all the corrupted documents for you.

  • Repair various corrupted files, including repairing Word, Excel, and PDF document 
  • Fix unreadable contents in Word efficiently
  • Repair corrupted PDF files, extract the text, comments, labels, graphics, etc. 
  • Compatible with Microsoft Office 2019, 2016, 2013, 2010, & previous versions.

Download the software and follow the detailed steps below to fix corrupted Excel files.

Step 1. Launch EaseUS Data Recovery Wizard, and then scan disk with corrupted documents. This software enables you to fix damaged Word, Excel, PPT, and PDF files in same steps. 

select the disk with corrupted documents

Step 2. EaseUS data recovery and repair tool will scan for all lost and corrupted files. You can find the target files by file type or type the file name in the search box. 

find corrupted documents

Step 3. EaseUS Data Recovery Wizard can repair your damaged documents automatically. After file preview, you can click «Recover» to save the repaired Word, Excel, and PDF document files to a safe location.

repair corrrupt documents

The Bottom Line

After reading, you must have a thorough understanding of how to fix Runtime error 1004. If you can make sure that the Excel file you want to open is valid, then the first three methods would help you out.

Once you got a damaged Excel file, a professional file recovery tool is a wiser choice. EaseUS file repair software is highly recommended by many users & IT professionals to help you repair Word, Excel, PowerPoint, and PDF files. 

Four ways to fix runtime error 1004 in Excel:

Workable Solutions Step-by-step Troubleshooting
Fix 1. Delete the GWXL97.XLA Files Fix the Excel error 1004 is to find and delete the error file. Go to C:Program FilesMS OfficeOfficeXLSTART…Full steps
Fix 2. Check the Trust Access to the VBA Project Object Model Enable a VBA project trust option in Excel Trust Center to fix Excel error 1004. Open a blank Excel file…Full steps
Fix 3. Create Another Excel Template Start a new Excel workbook and make sure there is only one worksheet in it. Format the workbook first…Full steps
Fix 4. Repair Corrupted Excel File Repair corrupted Excel files with a file recovery tool. EaseUS file repair tool fixes severely corrupted XLS and XLSX files and retrieves everything from Excel…Full steps

Microsoft Visual Basic for Applications (VBA) is developed to help users write programs for the Windows operating system. It runs as an internal programming language in Microsoft Office, such as Word, Excel, and PowerPoint.

Some users have reported that when running VBA in an Excel chart or trying to generate a Macro in Excel documents, an error message popped up saying: Runtime error 1004. And then they find themselves cannot access the Excel files. If you have the same encounter as these users, this post is the right place for you. You can find both the reasons and the corresponding solutions of this error code on this page.

How to Fix Excel Error 104

Runtime Error Details

The error message contains more information than the error code 1004. Generally, follow the error code, you can see a brief description. The most repeated error messages are listed below:

  1. Runtime error 1004: Application or object-defined error.
  2. Runtime error 1004: Method Ranger of Object Worksheet failed.
  3. Runtime error 1004: Copy Method of Worksheet Class failed.

The Reason Why You See Runtime Error 1004 in Excel

If you want to know how to fix runtime error 1004 in Excel properly, you need to understand what leads to this issue. The following are the most prominent reasons.

  • Macro Name Error

The Macro you are running is copying the original worksheet to a workbook with a defined name that you did not save and close before running the Macro.

  • File Conflict

When opening the VBA Excel file, it gets conflicted with other programs.

  • Too Many Legend Entries

The Excel chart contains more legend entries than space available to display the legend entries on the chart.

  • Excel File Corruption

Your .xls files got corrupted, infected, or damaged.

Although many reasons would cause this Excel error 1004 problem, luckily, some valid methods can help users re-access the files. Let’s check them one by one.

Fix 1. Delete the GWXL97.XLA Files to Fix Runtime Error 1004 in Excel

The easiest method to fix the Excel error 1004 is to find and delete the error file.

Step 1. Go to C:Program FilesMS OfficeOfficeXLSTART.

Step 2. Find GWXL97.XLA file and delete it.

Step 3. Reopen your Excel file and check if the problem is solved.

Fix 2. Check the Trust Access to the VBA Project Object Model

Another solution you can try is to enable a VBA project trust option in Excel Trust Center. Follow the detailed steps and have a try.

Step 1. Open a blank Excel file and click «Files» on the upper left.

Step 2. Click Option and go to Trust Center.

Enter Excel Option

Step 3. Find and enter the Trust Center Settings.

Enter Trust Center Settings

Step 4. Under Macro Settings, tick the option of «Trust access to the VBA project object model.»

Trust Access to the VBA Project

Now you can check your Excel file.

Fix 3. Create Another Excel Template to Fix Runtime Error 1004 in Excel

This method could be a little bit complicated, but it’s useful and worth trying.

Step 1. Please start a new Excel workbook and make sure there is only one worksheet in it.

Step 2. Format the workbook first and then put the data you need onto it.

Step 3. Tap File > Save As, first enter the file name, and click the unfold arrow in Save as Type column.

Excel Save As

Excel 2003: Choose Excel 97-2003 Template.

Excel 2007 or Later: Choose Excel Template.

Choose the Right Template

Step 4. Click «Save» to confirm.

Now you can insert it programmatically by using the following code: Add Type:=pathfilename. The file name is the one you set when you create the new Excel template.

Fix 4. Repair Corrupted Excel Files Due to Error 1004 

If all the above solutions can’t help you out, then there is one possibility that the Excel file you want to open is damaged. To fix a damaged Excel file, you can rely on file repair software. EaseUS Data Recovery Wizard is a great choice.

With this tool, click the «Repair» button and wait for it to fix all the corrupted documents for you.

  • Repair various corrupted files, including repairing Word, Excel, and PDF document 
  • Fix unreadable contents in Word efficiently
  • Repair corrupted PDF files, extract the text, comments, labels, graphics, etc. 
  • Compatible with Microsoft Office 2019, 2016, 2013, 2010, & previous versions.

Download the software and follow the detailed steps below to fix corrupted Excel files.

Step 1. Launch EaseUS Data Recovery Wizard, and then scan disk with corrupted documents. This software enables you to fix damaged Word, Excel, PPT, and PDF files in same steps. 

select the disk with corrupted documents

Step 2. EaseUS data recovery and repair tool will scan for all lost and corrupted files. You can find the target files by file type or type the file name in the search box. 

find corrupted documents

Step 3. EaseUS Data Recovery Wizard can repair your damaged documents automatically. After file preview, you can click «Recover» to save the repaired Word, Excel, and PDF document files to a safe location.

repair corrrupt documents

The Bottom Line

After reading, you must have a thorough understanding of how to fix Runtime error 1004. If you can make sure that the Excel file you want to open is valid, then the first three methods would help you out.

Once you got a damaged Excel file, a professional file recovery tool is a wiser choice. EaseUS file repair software is highly recommended by many users & IT professionals to help you repair Word, Excel, PowerPoint, and PDF files. 

Excel VBA Ошибка 1004

Ошибка VBA 1004 — это ошибка, с которой мы сталкиваемся при выполнении кода в VBA. Он также известен как ошибка времени выполнения VBA. Когда мы работаем в VBA или на любом другом языке программирования или даже в нашей повседневной работе, мы сталкиваемся с различными видами ошибок. Иногда даже мы пропускаем один символ в коде, что приводит к тому, что весь код не работает или, возможно, весь код неверен.

Ошибки, безусловно, являются частью кода, который мы пишем. Это может быть непреднамеренным, но они существуют. Независимо от того, насколько мы профессиональны в кодировании, ошибки во время выполнения могут возникнуть где угодно. Как объяснено выше VBA 1004 Ошибка — это ошибка, которая возникает во время выполнения кода в Excel. Это также называется ошибкой приложения или объекта.

Существуют различные типы причин, по которым мы получаем VBA Runtime Error 1004 в Excel, давайте рассмотрим некоторые из них.

  • Ошибка выполнения VBA 1004: сбой метода «Диапазон» объекта «_ Global»:

Эта ошибка возникает, когда значение диапазона, которое мы ссылаемся на VBA, неверно. Он также называется метод «Диапазон» объекта «_ Global» не удалось.

  • Ошибка выполнения VBA 1004: это имя уже занято. Попробуйте другой:

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

  • Ошибка выполнения VBA 1004: невозможно получить свойство select класса Range:

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

  • Ошибка выполнения VBA 1004: сбой метода «Открыть» объекта «Книги»:

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

  • Ошибка выполнения VBA 1004: извините, мы не смогли найти:

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

Как мы узнали, могут быть разные причины, по которым мы получаем ошибку во время выполнения. Ошибка выполнения может возникнуть в любой строке кода. Нам нужно научиться обрабатывать эти ошибки, и это называется VBA Error Handling.

Пример VBA Runtime Ошибка 1004 в Excel

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

Вы можете скачать этот шаблон Excel с ошибкой VBA 1004 здесь — Шаблон Excel с ошибкой VBA 1004

Ошибка выполнения VBA 1004 — Пример № 1

Как объяснено об этой ошибке, эта ошибка возникает, когда мы ссылаемся на неверное значение именованного диапазона в VBA. Это может произойти, если мы допустим орфографическую ошибку именованного диапазона, чтобы сослаться на диапазон, который даже не существует. Чтобы продемонстрировать это, давайте сначала создадим именованный диапазон. У меня есть следующие данные здесь.

  • Давайте назовем этот заголовок таблицы как DATA .

  • Перейдите на вкладку Разработчик, нажмите на Visual Basic, чтобы открыть VB Editor.

  • Объявите подфункцию, чтобы начать писать код.

Код:

 Sub Sample () End Sub 

  • Вызовите заголовок, который мы назвали следующим кодом, написанным ниже.

Код:

 Sub Sample () Range ("Данные"). Выберите End Sub 

  • Когда мы запускаем код, мы видим в Excel, что он был выбран, поскольку мы правильно вызвали заголовок.

  • Теперь мы неправильно написали орфографию имени заголовка.

Код:

 Sub Sample () Range ("Dataa"). Выберите End Sub 

  • Запустите код еще раз, чтобы увидеть результат.

Мы получаем Excel VBA Runtime Ошибка 1004, потому что мы неправильно написали имя диапазона.

Ошибка выполнения VBA 1004 — Пример № 2

Мы получаем эту ошибку, когда пытаемся переименовать лист с именем, которое уже занято. Например, я переименовал лист 1 в « Ананд », и я постараюсь переименовать лист 2 в тот же, чтобы увидеть результат.

  • Перейдите на вкладку Разработчик, нажмите на Visual Basic, чтобы открыть VB Editor.
  • Объявите подфункцию, чтобы начать писать код.

Код:

 Sub Sample1 () End Sub 

  • Попробуйте переименовать лист 2 в Anand с помощью следующего кода ниже,

Код:

 Sub Sample1 () Worksheets ("Sheet2"). Name = "Anand" End Sub 

  • Запустите приведенный выше код и посмотрите результат.

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

Ошибка выполнения VBA 1004 — Пример № 3

Я попытаюсь добавить значение из листа 2 к переменной на листе 3. Но я не буду активировать лист 2 и посмотрю, что произойдет.

  • Перейдите на вкладку Разработчик, нажмите на Visual Basic, чтобы открыть VB Editor.
  • Объявите подфункцию, чтобы начать писать код.

Код:

 Sub Sample2 () End Sub 

  • Объявите две переменные A и B как целое число.

Код:

 Sub Sample2 () Dim A As Integer Dim B As Integer End Sub 

  • В переменной B сохраните значение A в дополнение к ячейке A1 листа 2.

Код:

 Sub Sample2 () Dim A As Integer Dim B As Integer B = A + Рабочие листы ("Sheet2"). Диапазон ("A1"). Выберите End Sub 

  • Давайте предположим, что код работает, и используем функцию msgbox для отображения значения B.

Код:

 Sub Sample2 () Dim A As Integer Dim B As Integer B = A + Рабочие листы ("Sheet2"). Диапазон ("A1"). Выберите MsgBox B End Sub 

  • Запустите код, чтобы увидеть полученный результат.

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

Ошибка выполнения VBA 1004 — Пример № 4

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

В этом примере я уже переименовал свою книгу в VBA 1004 Error.xlsm, и я попытаюсь снова открыть ее, которая уже открыта, и посмотреть, получу ли я ошибку VBA 1004.

  • Перейдите на вкладку Разработчик, нажмите на Visual Basic, чтобы открыть VB Editor.
  • Объявите подфункцию, чтобы начать писать код.

Код:

 Sub Sample3 () End Sub 

  • Объявите переменную в качестве рабочей книги.

Код:

 Sub Sample3 () Dim A As Workbook End Sub 

Попробуйте открыть книгу, которую мы уже открыли, с помощью следующего кода.

Код:

 Sub Sample3 () Dim A As Set Workbook Set wb = Workbooks.Open (" VBA 1004 Error.xlsm", ReadOnly: = True, CorruptLoad: = xlExtractData) End Sub 

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

Мы получаем эту ошибку, потому что мы уже открыли ту же книгу.

Ошибка выполнения VBA 1004 — Пример № 5

Мы получаем эту ошибку, когда пытаемся открыть книгу, которой не существует. Это в некоторой степени похоже на приведенную выше ошибку, поскольку VBA не может найти книгу.

  • Перейдите на вкладку Разработчик, нажмите на Visual Basic, чтобы открыть VB Editor.
  • Объявите подфункцию, чтобы начать писать код.

Код:

 Sub Sample4 () End Sub 

  • Попробуйте открыть любую книгу с помощью следующего кода,

Код:

 Sub Sample4 () Workbooks.Open Filename: = "C:  EDUCBA Content  April  VBA OR Function.xlsm" End Sub 

  • Я уже удалил лист с места.
  • Запустите код, чтобы увидеть результат.

Поскольку лист не существует в данном месте, мы получаем эту ошибку.

То, что нужно запомнить

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

Рекомендуемые статьи

Это было руководство к VBA 1004 Ошибка. Здесь мы обсудили Excel VBA Runtime Error 1004 вместе с практическими примерами и загружаемым шаблоном Excel. Вы также можете просмотреть наши другие предлагаемые статьи —

  1. Добавить или удалить панель ошибок в Excel
  2. VBA Пока Loop | MS Excel
  3. Понимание ошибок в Excel
  4. Использование IFError в VBA

Для клиента я создал кнопку «Глобальный шаблон с новым документом», в которой отображается пользовательская форма, позволяющая пользователю создать новый документ с помощью выбора шаблонов, например, «Письмо», «Счет-фактура» и т.д. Недавно мы добавили отчет «Выбор».

Код, выполненный из этой пользовательской формы, очень прост, используя, например,

Documents.Add Template:="Letter.dotm", NewTemplate:=False

для создания новых документов.

Шаблон отчета — по моим стандартам — довольно сложный, с макросами AutoNew и AutoClose, EventClassModule, он записывает и считывает из CustomDocumentProperties, открывает несколько документов Word, где он копирует текст и вставляет его в документ отчета и т.д.

В первый раз, когда создается новый отчет, он работает так, как планировалось; но во второй раз (в том же сеансе Word) используется параметр «Отчет», появляется «Ошибка выполнения 5460». И после этого любой из других параметров документа возвращает ту же ошибку.

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

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

Проблема возникает в Word 2016 (365) с Windows 7 Pro, но не в Word 2013 с Windows 10.

Кто-нибудь, кто когда-либо испытывал подобное? Помощь очень ценится.

Ошибка выполнения 5460: «Произошла ошибка файла».

Отладка невозможна.

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

Как сказано, шаблон отчета отлично работает при использовании в проводнике, а при вызове через глобальный шаблон в 2013 году все работает.

Задача решена! Я последовал совету @macropod и добавил путь. Вместо того, чтобы просто использовать

'…
If OptionButton3.Value = True Then
Documents.Add Template:="Report.dot", NewTemplate:=False
End If
'…

Я изменил код на:

Private Sub CommandButton1_Click()

Dim strPath As String
strPath = Options.DefaultFilePath(wdWorkgroupTemplatesPath)

Dim wdApp As Word.Application
Set wdApp = GetObject(, "Word.Application")

'…
If OptionButton3.Value = True Then
wdApp.Documents.Add Template:=strPath & "Report.dot", NewTemplate:=False
End If
'…

End Sub

Спасибо!!

For a customer, I have created a Global template with a ’New Document” button that shows a userform letting the user create a new document from a choice of templates, e.g. Letter, Invoice, etc.
Recently, we have added the choice Report.

The code executed from this userform is very simple, using e.g.

Documents.Add Template:="Letter.dotm", NewTemplate:=False

to create the new documents.

The Report template is – by my standards – quite complex, with AutoNew and AutoClose macros, an EventClassModule, it writes to and reads from the CustomDocumentProperties, opens several specific Word documents from where it copies text and pastes it into the Report document, etc.

The first time a new Report is created it works as planned; but the second time (in the same Word session) the Report option is used, a ‘Runtime Error 5460’ occurs. And after that, any of the other document options returns the same error.

Quitting Word and starting a new Word session sets everything back to normal, until the Report template again is called the second time.

Strangely enough, the Report template works with no errors when new documents based on it are created directly from Explorer, as many times in the same Word session as needed.

The problem occurs in Word 2016 (365) with Windows 7 Pro, but not in Word 2013 with Windows 10.

Anybody that has ever experienced anything like this?? Help is really appreciated.


Runtime Error 5460: ‘A file error has occured.’

Debug is not possible.

The Report template has thousands of lines of code and I have not been able to find out if it is in fact code in the Report template that causes the error, or code in the Global template.

As said, the Report template works fine when used from Explorer, and when called via the Global template in 2013 everything works there too.


Problem solved!
I followed the advice from @macropod and added the path also.
In stead of just using

'…
If OptionButton3.Value = True Then
    Documents.Add Template:="Report.dot", NewTemplate:=False
End If
'…

I changed the code to:

Private Sub CommandButton1_Click()

Dim strPath As String
strPath = Options.DefaultFilePath(wdWorkgroupTemplatesPath)

Dim wdApp As Word.Application
Set wdApp = GetObject(, "Word.Application")

'…
If OptionButton3.Value = True Then
    wdApp.Documents.Add Template:=strPath & "Report.dot", NewTemplate:=False
End If
'…

End Sub

Thanks!!

Basically the macro opens a master document and takes sections of it and saves it as a number of other documents.

The line of code that makes the file save fail on the first of these is

Selection.FormattedText = thisPar.Range.FormattedText

in the bit of code below. This is only run for the first section and therefore file to be saved. All the others work.

This bit selects a content control then loops through the paragraphs in the section from the master document that will form the new doc and sets the indent to zero and the first paragraph it should put in the selected content control. Using Formattedtext to preserve formatting.

This line when present causes file save to fail with the above error, removing it and the file save works ok.

There is a similar bit of code putting the rest of the section into another content control, but this doesn’t seem to cause a problem.

Any idea what might be wrong and what alternatives are there?

          Set cc = cmsDoc.SelectContentControlsByTitle(«View or Abstract»).Item(1)
          cc.Range.Select

         
          intPCounter = 1

         
          ‘ loop through the paragraphs in this section and set indent to 0. Also write the first
          ‘ paragraph to «View or Abstract»
          For Each thisPar In section.Paragraphs
            thisPar.LeftIndent = 0
            If intPCounter = 1 Then

Selection.FormattedText = thisPar.Range.FormattedText

            End If
            intPCounter = intPCounter + 1
          Next thisPar

         
          Set cc = cmsDoc.SelectContentControlsByTitle(«Initial Body Text»).Item(1)
          cc.Range.Select
          Selection.FormattedText = section.FormattedText

Doug Robbins — Word MVP


  • #2

What is in the string fileName$? I would always use & to concatenate
strings and reserve + for arithmetic addition.


Hope this helps.

Please reply to the newsgroup unless you wish to avail yourself of my
services on a paid consulting basis.

Doug Robbins — Word MVP

Doug Robbins — Word MVP


  • #5

What is the present format of the document? The .FullName will include the
extension and you may have to strip it off.


Hope this helps.

Please reply to the newsgroup unless you wish to avail yourself of my
services on a paid consulting basis.

Doug Robbins — Word MVP

  • Runtime error 3146 odbc ошибка вызова
  • Runtime error 216 at 0040505e ошибка
  • Runtime broker что это windows 10 ошибка
  • Runtime broker ошибка приложения память не может быть read
  • Runtime broker exe системная ошибка