Ошибка инициализации библиотек vba 1004

How to Fix Runtime Error 1004 in Excel? There are four effective methods for you to choose from. You can follow them one by one to re-access the influenced Excel file. And Stellar Toolkit for File Repair will also give a helping hand if your Excel files got damaged or corrupted

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. 

 

Молодое_Поколение

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

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

#1

12.09.2020 18:46:25

Доброго времени суток господа!Живу все хорошо, как тут макросы которые работали на протяжении полугода без нареканий, стали выдавать ошибку. Запускаю макросы через планировщик задач. Через планировщик выскакивает ошибка, если делать вручную все работает.
Подскажите пожалуйста, что за ошибка и как ее решить.

Текст ошибки:

Цитата
Run-time error ‘1004’:
Сбой инициализации источника данных.
Проверьте сервер или обратитесь к администратору базы данных. Убедитесь, что внешняя база данных доступна, и вновь повторите операцию. При повторении сообщения, создайте новый источник для подключения к базе данных.

Макросы:

Код
Sub ОБН_информации()
With ThisWorkbook.Connections("Запрос — ЗП_ПОЛНАЯ_ИНФА")
    .OLEDBConnection.BackgroundQuery = False
    .Refresh
    End With
Call КП_СТАТИСТИКА_ОБЩАЯ
    End Sub

Sub ОБН_посты()
    With ThisWorkbook.Connections("Запрос — ЗП_ПОЛНАЯ_ФИФА")
    .OLEDBConnection.BackgroundQuery = False
    .Refresh
    End With
End Sub

Впитываю знания, как борщ после тренировки ^^)

 

Ігор Гончаренко

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

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

#2

12.09.2020 22:47:43

Цитата
VBA. Как устранить ошибку

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

Изменено: Ігор Гончаренко12.09.2020 22:49:39

Программисты — это люди, решающие проблемы, о существовании которых Вы не подозревали, методами, которых Вы не понимаете!

 

Шутить получается, а подсказывать молодым к сожалению нет 😄

Впитываю знания, как борщ после тренировки ^^)

 

Андрей VG

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

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

Excel 2016, 365

#4

13.09.2020 08:41:00

Доброе время суток

Цитата
Молодое_Поколение написал:
а подсказывать молодым к сожалению нет

Чтобы что-то подсказать, нужно знать, что и как происходило ранее, что и как происходит сейчас. А при том объёме информации, что вы соизволили представить, можно только шутить: вернитесь в начало прошлого полугодия — гарантированно полгода будет работать :)

 

Михаил Л

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

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

#5

13.09.2020 08:41:52

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

Молодое_Поколение, начните искать обстоятельство, вызывающее ошибку. Например, закомментировав один из макросов, проверьте работает ли незакомментированный :)  макрос.

Код
'Sub ОБН_информации()
'With ThisWorkbook.Connections("Запрос — ЗП_ПОЛНАЯ_ИНФА")
'    .OLEDBConnection.BackgroundQuery = False
'    .Refresh
'    End With
'Call КП_СТАТИСТИКА_ОБЩАЯ
'    End Sub
 
Sub ОБН_посты()
    With ThisWorkbook.Connections("Запрос — ЗП_ПОЛНАЯ_ФИФА")
    .OLEDBConnection.BackgroundQuery = False
    .Refresh
    End With
End Sub

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

НА МЯСО В ПРОФИЛЕ

 

Молодое_Поколение

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

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

#6

13.09.2020 14:24:55

Михаил Л, когда вручную делаю, все работает отлично, закомментирую макрос — скорей всего сегодня вечером или завтра утром дам обратную связь

Цитата
Например, закомментировав один из макросов, проверьте работает ли незакомментированный   макрос.Код

искал ответы в гугле — некоторым помог вариант установки net framework — мне не помог ((

Андрей VG, в одной из тем Вы сказали что в такой проблеме вам помогла установка power BI — я так понял это не решение, это замена excel ?
Ваш комментарий:

https://www.planetaexcel.ru/forum/index.php?PAGE_NAME=message&FID=1&TID=89275

Впитываю знания, как борщ после тренировки ^^)

 

Молодое_Поколение

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

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

#7

13.09.2020 16:00:46

Когда ошибка вылетает подсвечивается желтым .Refresh

Код
Sub ОБН_посты()
    With ThisWorkbook.Connections("Запрос — ЗП_ПОЛНАЯ_ФИФА")
    .OLEDBConnection.BackgroundQuery = False
    .Refresh
    End With
End Sub

поможет ли Option Explicit?

Впитываю знания, как борщ после тренировки ^^)

 

Дмитрий(The_Prist) Щербаков

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

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

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

#8

13.09.2020 16:17:06

Цитата
Молодое_Поколение написал:
поможет ли , Option Explicit ?

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

Variable not defined или что такое Option Explicit и зачем оно нужно?

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

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

 

Дмитрий(The_Prist) Щербаков, отличный сайт возьму на заметку… а как наделить планировщик права? может все дело в «настройке источника данных» в PQ. Хотя вручную же работает….  

Впитываю знания, как борщ после тренировки ^^)

 

Дмитрий(The_Prist) Щербаков

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

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

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

#10

13.09.2020 18:43:24

Цитата
Молодое_Поколение написал:
а как наделить планировщик права?

не знаю…информации мало. ПК локальный? Или сетевой? Где источник расположен? На локали или на сетевом диске? Если написать простой код на VBS(который будет делать тоже самое, что планировщик) и запустить его руками с рабочего стола — будет работать код?

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

 

Михаил Л, закомментил ничего не поменялось, также не работает

Дмитрий(The_Prist) Щербаков, напишите пожалуйста какая необходима информация, комп локальный, мой домашний, скрипт запускал сам, не работает…. Видимо проблема не в excel потому что, все нормально работает вручную, а через vbs файл начинает выдавать ошибку

Впитываю знания, как борщ после тренировки ^^)

 

Равик

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

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

#12

06.10.2020 09:03:12

Цитата
Молодое_Поколение написал:
Живу все хорошо, как тут макросы которые работали на протяжении полугода без нареканий, стали выдавать ошибку.

У меня код несколько другой:

Код
 Workbooks(OBSHCHIY_ANALIZ_V2).Worksheets("SumUp").Range("A2").ListObject.QueryTable.Refresh BackgroundQuery:=False

Ну суть та же — обновление запроса.

У меня выдает такую же ошибку, НО!

1. На ПК коллеги не выдает.
2. Дома не выдает.
3. Через некоторое время и на моем рабочем ПК перестает выдавать.
4. Заменю макрос другим с такой же строчкой — снова выдает.

Мистика

 

Молодое_Поколение

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

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

#13

06.10.2020 15:37:56

Проблема решена!!!
Помог способ №1

https://lumpics.ru/how-to-reinstall-net-framework-in-windows-10/#helpgood

Впитываю знания, как борщ после тренировки ^^)

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

Ошибка VBA 1004 в Excel

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

Однако знание того, почему это происходит, поможет вам избежать этих ошибок в ближайшем будущем.

В этой статье мы обсудим одну из важных ошибок Excel «Ошибка VBA 1004».

Ошибка VBA 1004

Вы можете свободно использовать это изображение на своем веб-сайте, в шаблонах и т. Д. Пожалуйста, предоставьте нам ссылку с указанием авторстваСсылка на статью должна содержать гиперссылку
Например:
Источник: Ошибка VBA 1004 (wallstreetmojo.com)

6 основных ошибок выполнения Excel VBA 1004

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

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

Эта ошибка возникает при переименовании листа.

Если имя рабочего листа уже существует и если вы попытаетесь назначить то же имя другому листу, VBA выдаст ошибку времени выполнения 1004, заявив: «Имя уже занято. Попробуйте другой «.

Например, посмотрите на приведенный ниже код.

Код:

Sub Error1004_Example()

 Worksheets("Sheet2").Name = "Sheet1"

End Sub

Пример ошибки VBA 1004 1

Я пытаюсь переименовать лист 2 в лист 1. Но у меня уже есть лист с именем «Sheet1».

Пример ошибки VBA 1004 1-2

Если я запустил этот код с помощью клавиши F5 или вручную, я получу ошибку времени выполнения 1004: это имя уже занято. Попробуйте другой.

Пример ошибки VBA 1004 1-1

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

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

Обычно это происходит, когда мы пытаемся получить доступ к именованный диапазон в ExcelДиапазон имен в Excel — это имя, присвоенное диапазону для использования в будущем. Чтобы присвоить диапазону имя, сначала выберите диапазон данных, а затем вставьте в диапазон таблицу, затем введите имя диапазона из поля имени в левой части окна.читать далее с орфографической ошибкой или вообще отсутствует на листе, на который вы ссылаетесь.

Для этого я назвал диапазон ячеек «Заголовками», как показано на изображении ниже.

Пример ошибки 2 VBA 1004

Теперь, используя объект Range, я могу получить доступ к этому диапазону.

Код:

Sub Error1004_Example()

  Range("Headings").Select

End Sub

Пример ошибки VBA 1004 2-1

Если вы запустите этот код, нажав клавишу F5, то этот код выберет именованный диапазон.

Пример ошибки VBA 1004 2-2

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

Код:

Sub Error1004_Example()

  Range("Headngs").Select

End Sub

Пример 2-3 ошибки VBA 1004

Запустите этот код вручную или с помощью клавиши F5 и посмотрите результат.

Пример ошибки VBA 1004 2-4

# 3 — Ошибка времени выполнения VBA 1004: Ошибка выбора метода класса Range:

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

Например, посмотрите на приведенный ниже код.

Код:

Sub Error1004_Example()

  Worksheets("Sheet1").Range("A1:A5").Select

End Sub

Пример ошибки 3 VBA 1004

В приведенном выше коде говорится, что нужно выбрать ячейки от A1 до A5 на листе «Sheet1». Чтобы поэкспериментировать, моим текущим активным листом является «Лист2», а не «Лист1».

Я запущу этот код с помощью клавиши F5 или вручную, чтобы посмотреть, что произойдет.

Пример ошибки VBA 1004 3-1

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

# 4 — Ошибка выполнения VBA 1004, не удалось открыть объектные книги:

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

Например, посмотрите на приведенный ниже код.

Код:

Sub Error1004_Example()

   Dim wb As Workbook
    Set wb = Workbooks.Open("FileName.xls", ReadOnly:=True, CorruptLoad:=xlExtractData)

End Sub

Пример 3-2

Это вызовет ошибку ниже.

Пример 3-3

# 5 — Метод ошибки выполнения VBA 1004 К сожалению, мы не смогли найти:

Эта ошибка возникает из-за того, что вы пытаетесь открыть файл, которого нет по указанному пути. Его можно переместить, переименовать или удалить по указанному пути. Одна из причин этого из-за неправильного типа пути или имени файла с расширение ExcelРасширения Excel представляют формат файла. Это помогает пользователю сохранять различные типы файлов Excel в различных форматах. Например, .xlsx используется для простых данных, а XLSM используется для хранения кода VBA.читать далее.

Теперь взгляните на приведенный ниже код.

Код:

Sub Error1004_Example()

   Workbooks.Open Filename:="E:Excel FilesInfographicsABC.xlsx"

End Sub

Пример 4

Этот код требует открыть файл «ABC.xlsx» в указанном пути к папке.

Я точно знаю, что в указанном пути к папке нет файла. Если в указанной папке нет файла, мы получим Ошибка выполнения 1004 метод. Извините, но мы не смогли его найти.

Пример 4-1

# 6 — Ошибка выполнения VBA 1004 Ошибка активации класса диапазона методов:

Эта ошибка возникает в основном из-за активации диапазона ячеек без активации рабочего листа.

Например, посмотрите на приведенный ниже код.

Код:

Sub Error1004_Example()

  Worksheets("Sheet1").Range("A1:A5").Activate

End Sub

Пример 5

Эта ошибка очень похожа на ту, которую мы видели в Ошибка времени выполнения 1004: Ошибка выбора метода класса Range.

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

Пример 5-1

Потому что без активации листа мы не можем активировать в нем ячейки. Итак, сначала активируйте лист, а затем активируйте ячейки этого листа.

УЗНАТЬ БОЛЬШЕ >>

Post Views: 1 457

С самого начала Microsoft предоставила нам множество полезных приложений. В свое время приложения стали частью Microsoft Office. Microsoft Excel — одно из таких приложений, которое существует с первых дней существования компьютеров, и это программа, которая позволяет пользователям систематизировать формат и вычислять данные. Более того, он позволяет пользователям использовать формулы, используя систему электронных таблиц. Microsoft Excel используется многочисленными компаниями по всему миру для выполнения финансового анализа. Более того, MS Excel также поддерживает приложения Visual Basic, что означает, что вы можете добавить скрипт VBA, прикрепленный к вашей электронной таблице.

Другие офисные программы и MS Excel используют код VBA для множества функций, например, вы можете добавить кнопку в электронную таблицу, которая автоматически добавит данные. Такие функции очень полезны, когда вы собираетесь управлять большим объемом данных. Однако пользователи часто сообщают об ошибках, что у них есть лицо. Здесь мы обсуждаем конкретную ошибку времени выполнения VBA 1004. Возможные причины ошибки времени выполнения 1004 VBA — неверный синтаксис или код, отфильтрованные данные, повреждение MS Excel. Однако также возможно, что две программы конфликтуют при попытке открыть файл VBA одновременно.

Как исправить ошибку времени выполнения VBA 1004?

Оглавление

  • 1 Как исправить ошибку времени выполнения VBA 1004?

    • 1.1 Способ 1. Создать новый шаблон
    • 1.2 Способ 2. Удаление файла GWXL97.XLA
    • 1.3 Способ 3. Отладить код
  • 2 Вывод

Как исправить ошибку времени выполнения VBA 1004?

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

Способ 1. Создать новый шаблон

Помещение нового листа Excel в шаблон вместо копирования или дублирования существующего листа может решить проблему. Поэтому сначала попробуйте это.

Шаг 1) Сначала запустите Microsoft Excel и создайте новую книгу, затем удалите существующий лист, оставив только один. Вы можете отформатировать как хотите, чтобы создать шаблон по умолчанию. Нажмите на файл вариант в строке меню и выберите Сохранить как вариант.

Как исправить ошибку времени выполнения VBA 1004?

Шаг 2) Выберите Книга Excel опция, откроется окно файлового менеджера. Выберите каталог, в котором вы хотите сохранить свой шаблон.

Как исправить ошибку времени выполнения VBA 1004?

Шаг 3) Введите имя шаблона, затем выберите тип файла как .xlt для Excel 2003 и .xltx для Excel 2007 или новее. Нажми на Сохранить кнопку, и ваш шаблон будет сохранен. Теперь попробуйте запустить код VBA.

Способ 2. Удаление файла GWXL97.XLA

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

Шаг 1) Откройте Проводник.

Шаг 2) Перейдите в следующий каталог —

C: Program Files MSOffice Office XLSTART

Шаг 3) Вы увидите файл GWXL97.XLA в папке, выберите и нажмите кнопку удаления на клавиатуре или щелкните правой кнопкой мыши и выберите удалить. Теперь попробуйте запустить код VBA.

Способ 3. Отладить код

Вполне возможно, что ошибка 1004 возникает из-за неверного кода. Поэтому вам нужно будет написать правильный синтаксис и значение, чтобы код VBA отлично выполнялся. Может быть множество ошибок, которые могут быть результатом ошибки 1004, чтобы этого не произошло, вам нужно дважды проверить свой код и указать недопустимые строки. Например, Имя уже занято сообщение отображается с ошибкой 1004, если имя рабочего листа уже существует, и ему присвоено то же имя другому.

Если вы запустите код, он выдаст сообщение об ошибке 1004, поэтому попробуйте изменить имя и присвоить значения. Есть еще 1004 ошибки, связанные с недопустимым кодом VBA, например, сбой в диапазоне object_Global, поле класса Select Method of Range и многое другое. Каждый раз, когда будет отображаться сообщение, ошибки будут выделены ошибкой 1004, если ошибка связана с кодом VBA. Поэтому отлаживайте код с правильным синтаксисом и значениями.

Вывод

Код ошибки 1004 в Ms. Excel можно глупо исправить, отладив коды, исправив неверные строки, имена и значения. Более того, если проблема не связана с кодом, вы можете удалить файл XLA, который может конфликтовать с MS Excel при открытии файла VBA. Кроме того, вы можете попытаться создать новый шаблон с существующей Рабочей книгой, чтобы устранить проблему.

Выбор редактора:

  • Показывать дату значка панели задач Windows 10 маленькими значками
  • Изменить скорость курсора в последней версии Windows 10 2004
  • Открывайте торрент-файлы в Windows 10 или macOS
  • Как исправить ошибку «Расширение панели управления несовместимо с версией драйвера»
  • Сделайте снимок экрана с видео YouTube

Рахул изучает информатику и проявляет огромный интерес к темам в области технологий и криптовалюты. Большую часть времени он пишет, слушает музыку или путешествует по незнакомым местам. Он считает, что шоколад — это решение всех его проблем. Жизнь бывает, и кофе помогает.

Return to VBA Code Examples

In this Article

  • VBA Error 1004 – Object does not exist
  • VBA Error 1004 – Name Already Taken
  • VBA Error 1004 – Incorrectly Referencing an Object
  • VBA Error 1004 – Object Not Found

This tutorial will explain the VBA Error 1004- Application-Defined or Object-Defined Error.

VBA run-time error 1004 is known as an Application-Defined or Object-Defined error which occurs while the code is running. Making coding errors (See our Error Handling Guide) is an unavoidable aspect learning VBA but knowing why an error occurs helps you to avoid making errors in future coding.

VBA Error 1004 – Object does not exist

If we are referring to an object in our code such as a Range Name that has not been defined, then this error can occur as the VBA code will be unable to find the name.

Sub CopyRange()
  Dim CopyFrom As Range
  Dim CopyTo As Range
  Set CopyFrom = Sheets(1).Range("CopyFrom")
  Set CopyTo = Sheets(1).Range("CopyTo")
  CopyFrom.Copy
CopyTo.PasteSpecial xlPasteValues
End Sub

The example above will copy the values from the named range “CopyFrom” to the named range “CopyTo” – on condition of course that these are existing named ranges!  If they do not exist, then the Error 1004 will display.

VBA Error1004 1

The simplest way to avoid this error in the example above is to create the range names in the Excel workbook, or refer to the range in the traditional row and column format eg: Range(“A1:A10”).

VBA Error 1004 – Name Already Taken

The error can also occur if you are trying to rename an object to an object that already exists – for example if we are trying to rename Sheet1 but the name you are giving the sheet is already the name of another sheet.

Sub NameWorksheet()
  ActiveSheet.Name = "Sheet2"
End Sub

If we already have a Sheet2, then the error will occur.

VBA Error1004 2

VBA Error 1004 – Incorrectly Referencing an Object

The error can also occur when you have incorrectly referenced an object in your code. For example:

Sub CopyRange()
  Dim CopyFrom As Range
  Dim CopyTo As Range
  Set CopyFrom = Range("A1:A10")
  Set CopyTo = Range("C1:C10")
  Range(CopyFrom).Copy
  Range(CopyTo).PasteSpecial xlPasteValues
End Sub

This will once again give us the Error 10004

VBA Error1004 1

Correct the code, and the error will no longer be shown.

Sub CopyRange()
  Dim CopyFrom As Range
  Dim CopyTo As Range
  Set CopyFrom = Range("A1:A10")
  Set CopyTo = Range("C1:C10")
  CopyFrom.Copy
  CopyTo.PasteSpecial xlPasteValues
End Sub

VBA Error 1004 – Object Not Found

This error can also occur when we are trying to open a workbook and the workbook is not found – the workbook in this instance being the object that is not found.

Sub OpenFile()
 Dim wb As Workbook
 Set wb = Workbooks.Open("C:DataTestFile.xlsx")
End Sub

Although the message will be different in the error box, the error is still 1004.

VBA Error 1004 FileNotFound

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 save as

Learn More!

Некоторые люди жаловались на Excel ошибка времени выполнения 1004. С самого начала эта ошибка может показаться серьезной проблемой, но по правде говоря, это больше отвлекает, чем что-либо еще. Ошибка времени выполнения 1004 может возникнуть, если Excel не получает доступ к Microsoft Visual Basic для приложений (VBA) или макросам.

Ошибка Excel 1004

Мы говорим это потому, что ошибку времени выполнения 1004 легко исправить, поэтому люди не должны терять из-за нее голову. Да, мы понимаем, что это замедляет ваш рабочий процесс, но как только вы поймете, как вращать вещи, все будет в порядке. Теперь необходимо указать, что любой, кто столкнется с этой ошибкой, не сможет использовать определенные библиотеки ресурсов. Кроме того, могут возникать проблемы с производительностью и постоянные сбои, что еще больше затрудняет использование Excel.

Что такое ошибка времени выполнения 1004 в Excel

По нашему опыту, ошибка появляется в основном, когда пользователь пытается запустить макрос MS Visual Basic для приложений. Все это является процедурой безопасности для блокировки MS VBA из Excel, но если пользователь решит предоставить ему доступ, то ошибка времени выполнения 1004, скорее всего, никогда не появится. Сообщение об ошибке может иметь несколько вариантов, а именно:

  • Ошибка выполнения 1004: ошибка, определяемая приложением или объектом
  • Ошибка выполнения 1004: сбой метода копирования класса листа
  • Ошибка 1004: программный доступ к проекту Visual Basic не является доверенным.

Первое, что вам здесь потребуется, это открыть Параметры Excel, что очень просто. Просто откройте Microsoft Excel, затем нажмите «Файл» и выберите «Параметры».

Исправить ошибку 1004 в Excel

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

Наконец, нажмите на Доверять доступ к объектной модели проекта VBA, затем нажмите Ok кнопку и все тут.

Сканирование на наличие вредоносных программ

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

Microsoft Defender — отличный инструмент для этой работы, но если вам этого недостаточно, мы предлагаем использовать бесплатный автономный сканер вредоносных программ.

 Summary:

In this post, I have included the complete information about Excel runtime error 1004. Besides that I have presented some best fixes to resolve runtime error 1004 effortlessly.

To fix Runtime Error 1004 in Excel you can take initiatives like uninstalling Microsoft Work, creating a new Excel template, or deleting The “GWXL97.XLA” File. If you don’t have any idea on how to apply these methods then go through this post.

Here in this article, we are going to discuss different types of VBA runtime error 1004 in Excel along with their fixes.

What Is Runtime Error 1004 In VBA Excel?

Excel error 1004 is one such annoying runtime error that mainly encounters while working with the Excel file. Or while trying to generate a Macro in Excel document and as a result, you are unable to do anything in your workbook.

This error may cause serious trouble while you are working with Visual Basic Applications and can crash your program or your system or in some cases, it freezes for some time. This error is faced by any versions of MS Excel such as Excel 2007/2010/2013/2016/2019 as well.

To recover lost Excel data, we recommend this tool:

This software will prevent Excel workbook data such as BI data, financial reports & other analytical information from corruption and data loss. With this software you can rebuild corrupt Excel files and restore every single visual representation & dataset to its original, intact state in 3 easy steps:

  1. Download Excel File Repair Tool rated Excellent by Softpedia, Softonic & CNET.
  2. Select the corrupt Excel file (XLS, XLSX) & click Repair to initiate the repair process.
  3. Preview the repaired files and click Save File to save the files at desired location.

Error Detail:

Error Code: run-time error 1004

Description: Application or object-defined error

Screenshot Of The Error:

run-time error 1004

Don’t worry you can fix this Microsoft Visual Basic runtime error 1004, just by following the steps mentioned in this post. But before approaching the fixes section catch more information regarding runtime error 1004.

Excel VBA Run Time Error 1004 Along With The Fixes

EXCEL ERRORS

The lists of error messages associated with this Excel error 1004 are:

  1. VB: run-time error ‘1004’: Application-defined or object-defined error
  2. Excel VBA Runtime error 1004 “Select method of Range class failed”
  3. runtime error 1004 method range of object _global failed visual basic
  4. Excel macro “Run-time error ‘1004″
  5. Runtime error 1004 method open of object workbooks failed
  6. Run time error ‘1004’: Method ‘Ranger’ of Object’ Worksheet’ Failed
  7. Save As VBA run time Error 1004: Application defined or object defined error

Let’s discuss each of them one by one…!

#1 – VBA Run Time Error 1004: That Name is already taken. Try a different One

This VBA Run Time Error 1004 in Excel mainly occurs at the time of renaming the sheet.

If a worksheet with the same name already exists but still you are assigning that name to some other worksheet. In that case, VBA will throw the run time error 1004 along with the message: “The Name is Already Taken. Try a different one.”

VBA Run Time Error 1004 in Excel 1

Solution: You can fix this error code by renaming your Excel sheet.

#2 – VBA Run Time Error 1004: Method “Range” of object’ _ Global’ failed

This VBA error code mainly occurs when someone tries to access the object range with wrong spelling or which doesn’t exist in the worksheet.

Suppose, you have named the cells range as “Headings,” but if you incorrectly mention the named range then obviously you will get the Run Time Error 1004: Method “Range” of object’ _ Global’ failed error.

VBA Run Time Error 1004 in Excel 2

Solution: So before running the code properly check the name of the range.

# 3 – VBA Run Time Error 1004: Select Method of Range class failed

This error code occurs when someone tries to choose the cells from a non-active sheet.

 Let’s understand with this an example:

Suppose you have selected cells from A1 to A5 from the Sheet1 worksheet. Whereas, your present active worksheet is Sheet2.

At that time it’s obvious to encounter Run Time Error 1004: Select Method of Range class failed.

VBA Run Time Error 1004 in Excel 3

Solution: To fix this, you need to activate the worksheet before selecting cells of it.

#4 – VBA Runtime Error 1004 method open of object workbooks failed

This specific run time Error 1004 arises when someone tries to open an Excel workbook having the same workbook name that is already open.

In that case, it’s quite common to encounter VBA Runtime Error 1004 method open of object workbooks failed.

VBA Run Time Error 1004 in Excel 4

Solution: Well to fix this, first of all close the already opened documents having a similar name.

#5 – VBA Runtime Error 1004 Method Sorry We Couldn’t Find:

The main reason behind the occurrence of this VBA error in Excel is due to renaming, shifting, or deletion of the mentioned path.

The reason behind this can be the wrong assigned path or file name with extension.

When your assigned code fails to fetch a file within your mentioned folder path. Then you will definitely get the runtime Error 1004 method. Sorry, and We couldn’t find it.

VBA Run Time Error 1004 in Excel 5

Solution: make a proper check across the given path or file name.

#6 – VBA Runtime Error 1004 Activate method range class failed

Behind this error, the reason can be activating the cells range without activating the Excel worksheet.

This specific error is quite very similar to the one which we have already discussed above i.e Run Time Error 1004: Select Method of Range class failed.

VBA Run Time Error 1004 in Excel 6

Solution: To fix this, you need to activate your excel sheet first and then activate the sheet cells. However, it is not possible to activate the cell of a sheet without activating the worksheet.

Why This Visual Basic Runtime Error 1004 Occurs?

Follow the reasons behind getting the run time error 1004:

  1. Due to corruption in the desktop icon for MS Excel.
  2. Conflict with other programs while opening VBA Excel file.
  3. When filtered data is copied and then pasted into MS Office Excel workbook.
  4. Due to application or object-defined error.
  5. A range value is set programmatically with a collection of large strings.

Well, these are common reasons behind getting the VBA runtime error 1004, now know how to fix it. Here we have described both the manual as well as automatic solution to fix the run time error 1004 in Excel 2016 and 2013. In case you are not able to fix the error manually then make use of the automatic MS Excel Repair Tool to fix the error automatically.

Fix Runtime Error 1004

Follow the steps given below to fix Excel run time error 1004 :

1: Uninstall Microsoft Work

2: Create New Excel Template

3: Delete The “GWXL97.XLA” File

Method 1: Uninstall Microsoft Work

1. Go to the Task Manager and stop the entire running programs.

2. Then go to Start menu > and select Control Panel.

run time error 1004 (1)

3. Next, in the Control Panel select Add or Remove Program.

run time error 1004 (2)

4. Here, you will get the list of programs that are currently installed on your PC, and then from the list select Microsoft Work.

run time error 1004

5. And click on uninstall to remove it from the PC.

It is also important to scan your system for viruses or malware, as this corrupts the files and important documents. You can make use of the best antivirus program to remove malware and also get rid of the runtime error 1004.

Method 2: Create New Excel Template

Another very simple method to fix Excel runtime error 1004 is by putting a new Excel worksheet file within a template. Instead of copying or duplicating the existing worksheet.

Here is the complete step on how to perform this task.

1.Start your Excel application.

2. Make a fresh new Excel workbook, after then delete the entire sheets present on it leaving only a single one.

3. Now format the workbook as per your need or like the way you want to design in your default template.

4. Excel 2003 user: Tap to the File>Save As option

SAVE EXCEL FILE

OR Excel 2007 or latest versions: Tap to the Microsoft Office button after then hit the Save As option.

SAVE EXCEL FILE 1

5. Now in the field of File name, assign name for your template.

6. On the side of Save as type there is a small arrow key, make a tap on it. From the opened drop menu

  • Excel 2003 users have to choose the Excel Template (.xlt)

Create New Excel Template 1

  • And Excel 2007 or later version have to choose the Excel Template (.xltx)

Create New Excel Template 2

7. Tap to the Save.

8. After the successful creation of the template, now you can programmatically insert it by making use of the following code:
Add Type:=pathfilename

Remarks: 

From the above code, you have to replace the pathfilename with the complete path including the file name. For assigning the exact location of the sheet template you have just created.

Method 3: Delete The “GWXL97.XLA” File

Follow another manual method to fix Excel Runtime Error 1004:

1. Right-click on the start menu.

2. Then select the Explore option.

Excel Runtime Error 1004

3. Then open the following directory – C:Program FilesMSOfficeOfficeXLSTART

Excel Runtime Error 1004 (1)

4. Here you need to delete “GWXL97.XLA” file

Excel Runtime Error 1004 (2)

5. And open the Excel after closing the explorer

You would find that the program is running fine without a runtime error. But if you are still facing the error then make use of the automatic MS Excel Repair Tool, to fix the error easily.

Automatic Solution: MS Excel Repair Tool

MS Excel Repair Tool is a professional recommended solution to easily repair both .xls and .xlsx file. It supports several files in one repair cycle. It is a unique tool that can repair multiple corrupted Excel files at one time and also recover everything included charts, cell comments, worksheet properties, and other data. This can recover the corrupt Excel file to a new blank file. It is extremely easy to use and supports both Windows as well as Mac operating systems.

* Free version of the product only previews recoverable data.

Steps to Utilize MS Excel Repair Tool:

Conclusion:

Hope this article helps you to repair the runtime error 1004 in Excel and recovers Excel file data. In this article, we have provided a manual as well as automatic solution to get rid of Excel run-time error 1004. You can make use of any solution according to your desire.

Good Luck!!!

Priyanka is an entrepreneur & content marketing expert. She writes tech blogs and has expertise in MS Office, Excel, and other tech subjects. Her distinctive art of presenting tech information in the easy-to-understand language is very impressive. When not writing, she loves unplanned travels.

VBA Runtime Error 1004 occurs while you are executing a macro in Excel. It’s an error that can occur due to several reasons. In the below example, as you can see, when I run the code, it shows the run-time error ‘1004’. In simple words, you can also say it occurs when you can’t perform an activity with the object or the application.

In this tutorial, we will understand several other reasons for this runtime 1004 error.

Error1: VBA Run Time Error 1004: That Name is already taken. Try a different One:

As I shared above, when you try to add a sheet with the name that is already there in the workbook using a VBA code, VBA shows you a run-time error with the 1004 code.

Even when you try to rename a worksheet, you’ll get the same error from VBA.

In the above code, I tried to rename the sheet “Sheet2” with the name “Sheet1”, but as you can see, I already have the “Sheet1” in the workbook; VBA showed me the error code 1004.

To deal with this problem is to check if a sheet already exists in the workbook or not.

Error2: VBA Run Time Error 1004: Method “Range” of object’ _ Global’ failed:

As you know, you can create a named range in Excel, but when you try to refer to that named range using a VBA code, and you misspelled its name, you are likely to get the run-time error 1004 Method “Range” of object’ _ Global’ failed.

In the following example, I have a named range with the name “myRange”, but while writing the macro, I have misspelled it as “myRang” even though it’s a typing mistake; VBA is not that smart to identify this mistake, and refer to the correct named range.

There is no named range with the name that I have mentioned, and that is why it showed me the run-time error 1004.

Error3: VBA Run Time Error 1004: Select Method of Range class failed:

When you use a VBA code to select a range that is not in the active worksheet, VBA will show you the run-time error 1004. Because, if you want to select a cell or range of cells for a particular worksheet needs to be active at that point.

You cannot select a cell from sheet1 if sheet2 is active right now.

As you can see in the following example, I have made the same mistake where I’m referring to cell A1 from sheet one, but sheet2 is active.

The best way to deal with this error is to activate the sheet first and then write a line of code that selects a cell or the range from that sheet. You can also check if a sheet is active or not and then select the cell from that sheet, and if somehow that sheet is not active, you can show a message to the user to activate that sheet first.

Error4: VBA Runtime Error 1004 Activate method range class failed:

Just like the above reason, when you try to activate a cell or range of cells from a specific worksheet that is not active at the moment, we will show you runtime error 1004 (Activate method range class failed:).

In the about example when I tried to activate cell A1 in the sheet1 it gave me runtime error 1004, is the active sheet was the sheet2.

To deal with this error again you need to verify that the worksheet that you are referring to is active or not. Or you can also verify if that sheet is there in the workbook or not.

Error5: VBA Runtime Error 1004 method Sorry We couldn’t Find:

If you’re trying to open an Excel file using a path, but that workbook is not there, maybe it has been moved, deleted, or renamed. In that case, VBA will again show you a run-time error of 1004.

That’s what happened in the following example where I tried to open the file with the path from my desktop, but that file is not there, and it has shown me an error.

To deal with the situation, you can use a VBA code to verify if the file that you are referring to is there in the folder or not.

Error6: VBA Runtime Error 1004 method open of object workbooks failed:

This error is also related to the workbook. So when you try to open a workbook with the name for which a book already exists and is open at the moment, VBA will show you the run-time error 1004 (method open of object workbooks failed).

The same thing happened in the above example, where I tried to open a workbook that is already open, and VBA showed me a run time error (1004).

How to Correct VBA’s Runtime (Error 1004)

Error 1004 is a run-time error that occurs while executing a VBA code. And all the errors that we have discussed above are due to human errors while writing the code, following the points you can use to avoid the run-time error 1004.

  1. Do a step-by-step code execution to see on which line the error occurs.
  2. Make sure to verify all the names of the workbooks that you are referring to.
  3. You can also use a VBA code to verify if a workbook is already opened or not.
  4. And use the activate method to activate a worksheet before you refer to a cell or range from it.

More on VBA Errors

Subscript Out of Range (Error 9) | Type Mismatch (Error 13) | Object Required (Error 424) | Out of Memory (Error 7) | Object Doesn’t Support this Property or Method (Error 438) | Invalid Procedure Call Or Argument (Error 5) | Overflow (Error 6) | Automation error (Error 440) | VBA Error 400

Понравилась статья? Поделить с друзьями:
  • Ошибка импорта pd2 ответ сервера не опознан
  • Ошибка инициализации авест белинвестбанк
  • Ошибка збр 1088
  • Ошибка иммобилайзера форд фьюжн
  • Ошибка инициализации whatsapp