Ошибка runtime error 1004 vba

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. 

I am having an issue with a Error 1004 «Application-defined or Object-defined error» when selecting a range.

I am still able to select rows (ie Rows("21:21").select) and to select ranges in other sheets of the same workbook. I do not believe the error is in the code. Maybe its some setting I am unaware of?

I have used the exact same code many times before but for some reason I cannot make it function in this sub (I have commented where the error occurs)…

Sub CopySheet1_to_PasteSheet2()

    Dim CLastFundRow As Integer
    Dim CFirstBlankRow As Integer

    'Finds last row of content
    Windows("Excel.xlsm").Activate
    Sheets("Sheet1").Activate
    Range("C21").Select
         '>>>Error 1004 "Application-defined or Object-defined error" Occurs
    Selection.End(xlDown).Select
    CLastFundRow = ActiveCell.Row
    'Finds first row without content
    CFirstBlankRow = CLastFundRow + 1

    'Copy Data
    Range("A21:C" & CLastFundRow).Select
    Selection.Copy
    'Paste Data Values
    Sheets("PalTrakExport PortfolioAIdName").Select
    Range("A21").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False

    'Bring back to top of sheet for consistancy
    Range("A21").Select
    Range("A1").Select
End Sub

I need to get all fancy in my copying as the amount of rows will change frequently. Again, the below code has been used before without error… but not in this instance.

Dim CLastFundRow As Integer
Dim CFirstBlankRow As Integer

'Finds last row of content
Windows("Excel.xlsm").Activate
Sheets("Sheet1").Activate
Range("C21").Select
     '>>>Error 1004 "Application-defined or Object-defined error" Occurs
Selection.End(xlDown).Select
CLastFundRow = ActiveCell.Row
'Finds first row without content
CFirstBlankRow = CLastFundRow + 1

MackM's user avatar

MackM

2,8365 gold badges32 silver badges44 bronze badges

asked Jul 31, 2013 at 20:58

thomas's user avatar

1

Perhaps your code is behind Sheet1, so when you change the focus to Sheet2 the objects cannot be found? If that’s the case, simply specifying your target worksheet might help:

Sheets("Sheet1").Range("C21").Select

I’m not very familiar with how Select works because I try to avoid it as much as possible :-). You can define and manipulate ranges without selecting them. Also it’s a good idea to be explicit about everything you reference. That way, you don’t lose track if you go from one sheet or workbook to another. Try this:

Option Explicit

Sub CopySheet1_to_PasteSheet2()

    Dim CLastFundRow As Integer
    Dim CFirstBlankRow As Integer
    Dim wksSource As Worksheet, wksDest As Worksheet
    Dim rngStart As Range, rngSource As Range, rngDest As Range

    Set wksSource = ActiveWorkbook.Sheets("Sheet1")
    Set wksDest = ActiveWorkbook.Sheets("Sheet2")

    'Finds last row of content
    CLastFundRow = wksSource.Range("C21").End(xlDown).Row
    'Finds first row without content
    CFirstBlankRow = CLastFundRow + 1

    'Copy Data
    Set rngSource = wksSource.Range("A2:C" & CLastFundRow)

    'Paste Data Values
    Set rngDest = wksDest.Range("A21")
    rngSource.Copy
    rngDest.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
    'Bring back to top of sheet for consistancy
    wksDest.Range("A1").Select

End Sub

answered Jul 31, 2013 at 22:58

Frank H.'s user avatar

Frank H.Frank H.

88611 silver badges21 bronze badges

1

It’s a bit late but might be helpful for future reference. I had just had the same issue and I think it’s because the macro was placed at the worksheet level. Right click on the modules node on the VBA project window, click on «Insert» => «Module», then paste your macro in the new module (make sure you delete the one recorded at the worksheet level).

ZygD's user avatar

ZygD

20.6k39 gold badges75 silver badges96 bronze badges

answered May 30, 2014 at 4:58

Kam's user avatar

KamKam

2713 silver badges2 bronze badges

2

I as well had the same problem and nearly drove crazy. The solution was pretty unexpected.

My Excel is shipped out by default that I enter formulas in an Excel-Cell as followed:

=COUNTIF(Range; Searchvalue)
=COUNTIF(A1:A10; 7) 'Example

Please note, that parameters are separated with a semicolon;. Now if you paste exactly that string into a formula within VBA, for example like:

Range("C7").FormulaArray = "=COUNTIF(A1:A10; 7)" 'this will not work

You will get this 1004-error with absolutely no explanation. I spent hours to debug this.. All you have to do is replace all semicolon with commas.

Range("C7").FormulaArray = "=COUNTIF(A1:A10, 7)" 'this works

answered Jul 5, 2018 at 5:55

Zim84's user avatar

Zim84Zim84

3,3742 gold badges34 silver badges40 bronze badges

4

The same thing happened to me. In my case most of the worksheet was in protected mode (though the cells relevant to the macro were unlocked). When I disabled the protection on the worksheet, the macro worked fine…it seems VBA doesn’t like locked cells even if they are not used by the macro.

answered May 30, 2014 at 12:38

Emily's user avatar

EmilyEmily

911 silver badge1 bronze badge

Some operations in Excel are limited by available Memory. If you repeat the same process over and over it could produce a memory overflow and excel will not be able to repeat it anymore. This happened to me while trying to create several sheets in the same workbook.

The Guy with The Hat's user avatar

answered Mar 29, 2014 at 13:36

Dave's user avatar

You may receive a «Run-time error 1004» error message when you programmatically set a large array string to a range in Excel 2003

In Office Excel 2003, when you programmatically set a range value with an array containing a large string, you may receive an error message similar to the following:

Run-time error ‘1004’. Application-defined or operation-defined error.

This issue may occur if one or more of the cells in an array (range of cells) contain a character string that is set to contain more than 911 characters.

To work around this issue, edit the script so that no cells in the array contain a character string that holds more than 911 characters.

For example, the following line of code from the example code block below defines a character string that contains 912 characters:

Sub XLTest()
Dim aValues(4)

  aValues(0) = "Test1"
  aValues(1) = "Test2"
  aValues(2) = "Test3"

  MsgBox "First the Good range set."
  aValues(3) = String(911, 65)

  Range("A1:D1").Value = aValues

  MsgBox "Now the bad range set."
  aValues(3) = String(912, 66)
  Range("A2:D2").Value = aValues

End Sub

Other versions of Excel or free alternatives like Calc should work as well.

answered May 30, 2016 at 11:19

Cees Timmerman's user avatar

Cees TimmermanCees Timmerman

16.7k10 gold badges91 silver badges122 bronze badges

You need to find out the actual reason for this common error code: 1004. Edit your function/VBA code and run your program in debug mode to identify the line which is causing it. And then, add below piece of code to see the error,

On Error Resume Next
//Your Line here which causes 1004 error
If Err.Number > 0 Then
  Debug.Print Err.Number & ":" & Err.Description
End If

Note:
Debug shortcut keys i use in PC:
Step Into (F8), Step Over (Shift + F8), Step Out (Ctrl + Shift + F8)

answered Apr 16, 2018 at 4:08

Bhuvanesh Mani's user avatar

I could remove the error (Run-time error ‘1004’. Application-defined or operation-defined error) by defining the counters as Single

answered Jan 6, 2017 at 12:47

Rolf's user avatar

You can use the following code (For example if one was to want to copy cell data from Sheet2 to Sheet1).

Sub Copy
Worksheets("Sheet1").Activate                    
Worksheets("Sheet1").Range(Cells(i, 6), Cells(i, FullPathLastColumn)).Copy_
Destination:=Worksheets("Sheet2").Cells(Path2Row, Path2EndColumn + 1)
End Sub

DecstarG's user avatar

DecstarG

1212 silver badges15 bronze badges

answered Aug 31, 2016 at 13:20

parpaei's user avatar

1

I had a similar issue, but it turns out I was just referencing a cell which was off the page {i.e. cells(i,1).cut cells (i-1,2)}

Andreas Covidiot's user avatar

answered Mar 20, 2017 at 15:07

WannabeProger's user avatar

I had a similar problem & fixed it applying these steps:

  1. Unprotecting the sheet that I want to edit
  2. Changing the range that I had selected by every single cell in the range (exploded)

I hope this will help someone.

batman's user avatar

batman

1,9732 gold badges22 silver badges40 bronze badges

answered Aug 9, 2016 at 3:50

Fabian's user avatar

You have to go to the sheet of db to get the first blank row, you could try this method.

Sub DesdeColombia ()    
  Dim LastRowFull As Long

  'Here we will define the first blank row in the column number 1 of sheet number 1:
  LastRowFull = Sheet1.Cells(Rows.Count,1).End(xlUp).Offset(1,0).Row

  'Now we are going to insert information
  Sheet1.Cells(LastRowFull, 1).Value = "We got it"    
End Sub

DecstarG's user avatar

DecstarG

1212 silver badges15 bronze badges

answered Jul 28, 2016 at 14:39

Alex Merlano's user avatar

I had this issue during VBA development/debugging suddenly because some (unknown to me) function(ality) caused the cells to be locked (maybe renaming of named references at some problematic stage).

Unlocking the cells manually worked fine:

Selecting all worksheet cells (CTRL+A) and unlock by right click -> cell formatting -> protection -> [ ] lock (may be different — translated from German: Zellen formatieren -> Schutz -> [ ] Gesperrt)

answered Jun 5, 2019 at 8:50

Andreas Covidiot's user avatar

Andreas CovidiotAndreas Covidiot

4,1385 gold badges49 silver badges95 bronze badges

I had a similar issue when trying to loop on each sheet of a workbook.
To resolve it I did something like this

dim mySheet as sheet

for each mysheet in myWorkbook.sheets

    mySheet.activate
    activesheet.range("A1").select

    with Selection
    'any wanted operations here
    end with

next

And it worked just fine

I hope you can adapt it in your situation

Mogsdad's user avatar

Mogsdad

44.1k21 gold badges151 silver badges272 bronze badges

answered May 4, 2016 at 21:27

user6292909's user avatar

I ran into the same issue and found that the individual that created the worksheet had several columns locked. I removed the protection and everything worked as designed.

answered Feb 20, 2017 at 18:04

Chris Cooksey's user avatar

I am also having the same problem and I solved by as below.
in macro have a variable called rownumber and initially i set it as zero. this is the error because no excel sheet contains row number as zero. when i set as 1 and increment what i want.
now its working fine.

answered Feb 14, 2018 at 5:16

Singaravelan's user avatar

SingaravelanSingaravelan

7813 gold badges18 silver badges32 bronze badges

I also had a similar issue. After copying and pasting to a sheet I wanted the cursor/ selected cell to be A1 not the range that I just pasted into.

Dim wkSheet as Worksheet
Set wkSheet = Worksheets(<sheetname>)

wkSheet("A1").Select

but got a 400 error which was actually a 1004 error

You need to activate the sheet before changing the selected cell
this worked

Dim wkSheet as Worksheet
Set wkSheet = Worksheets(<sheetname>)

wkSheet.Activate
wkSheet("A1").Select

answered Apr 7, 2018 at 11:10

Dave Pile's user avatar

Dave PileDave Pile

5,3653 gold badges33 silver badges49 bronze badges

Just wanted to add an additional fix since I had previously never encountered it:

A user of mine was running into this runtime error with an Excel workbook he pulls information from, but only on his desktop computer even though its hardware and software were nearly identical to his laptop (same amount of memory, OS, Office configuration, etc.).

It turned out that the monitor connected to his desktop computer was too big — the solution/work around was to open a blank Excel file, make the Excel window smaller, then open the file he was having issues with.

Since this was a file generated by a third-party — we could not edit/implement any of the previously suggested fixes, nor did changing the macro or protection settings do anything (and they were working on his laptop with the same settings anyway).

answered Jul 17, 2021 at 17:21

mael''s user avatar

mael’mael’

4533 silver badges7 bronze badges

Майкрософт Эксель — одна из самых популярных электронных таблиц, используемых во всем мире как для личных, так и для деловых целей. Это универсальное место для хранения, организации и обработки данных организованным способом. MS Excel поставляется в основном с двумя расширениями, то есть в формате XLS и XLSX. Однако, помимо невероятной популярности, ошибки во время выполнения — обычная неприятность для очень многих пользователей Windows, и одной из самых распространенных является ошибка. Ошибка выполнения 1004.

Ошибка выполнения 1004 в Excel

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

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

Ошибка выполнения 1004 — это код ошибки, относящийся к Microsoft Visual Basic, который, как известно, беспокоит пользователей Microsoft Excel. С этой ошибкой сталкиваются любые версии MS Excel, такие как Excel 2007, 2010, 2013, 2016, 2019. Ни одна версия Microsoft Excel не застрахована от угрозы Runtime Error 1004.

С этой ошибкой в ​​основном сталкиваются пользователи, когда они работают с файлом Excel или пытаются создать макрос в документе Excel. Это может вызвать серьезные проблемы при работе с приложениями Visual Basic и привести к полному сбою программы или даже всей системы; иногда это может привести к зависанию системы, запрещая пользователям что-либо делать в своей системе.

Типы сообщений об ошибках

Сообщения об ошибках, которые больше всего связаны с этой ошибкой времени выполнения, следующие:

  • VB: ошибка времени выполнения ‘1004’: ошибка приложения или объекта
  • Ошибка выполнения Excel VBA 1004 «Ошибка выбора метода класса Range»
  • ошибка времени выполнения 1004 диапазон метода объекта _global не удалось Visual Basic
  • Макрос Excel «Ошибка выполнения» 1004?
  • Ошибка выполнения 1004 не удалось открыть метод объектных книг
  • Ошибка времени выполнения «1004»: сбой метода «Рейнджер» объекта «Рабочий лист»
  • «Сбой метода в ПРИЛОЖЕНИИ ПРИЛОЖЕНИЯ ОБЪЕКТНОЙ программы».

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

Каковы причины?

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

  • Значок рабочего стола MS Excel может быть поврежден
  • Файл VBA Excel конфликтует с другим приложением
  • Из-за ошибки, указанной в приложении или объекте
  • Из-за отсутствия зависимого файла
  • Из-за вируса, трояна или вредоносного ПО
  • Из-за неверных ключей реестра и так далее.

Это были некоторые из наиболее частых причин получения ошибки времени выполнения 1004 в MS Excel; Теперь давайте разберемся с различными исправлениями.

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

  1. Создать новый шаблон Excel
  2. Запустите сканирование на вирусы
  3. Для VB: ошибка времени выполнения ‘1004’, измените размер записей легенды

Давайте подробно рассмотрим каждый из этих методов.

1]Создайте новый шаблон Excel

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

1]Откройте MS Excel в вашей системе

2]Нажмите ‘CTRL + N‘для создания нового листа Microsoft Excel или просто выберите’Пустая книга‘с первого экрана.

Ошибка выполнения 1004

3]После этого удалите все листы в книге, кроме одного.

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

5]В конце перейдите к ‘Файл> Сохранить как‘, чтобы сохранить новый рабочий лист в формате файла шаблона Excel (.xltx или .xlt).

6]После успешного создания шаблона вы можете вставить его программно, используя следующую строку кода:

Таблицы.Добавить Тип: = путь имя файла

Пожалуйста, обрати внимание — Не забудьте заменить новое имя файла на настоящее имя документа.

2]Запустите сканирование на вирусы

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

3]Для VB: ошибка времени выполнения «1004», измените размер записей легенды.

Если вы столкнулись с ошибкой времени выполнения 1004 при запуске макроса Microsoft Visual Basic для приложений (VBA), вы можете использовать этот метод для временного решения.

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

Ошибка времени выполнения ‘1004’: ошибка приложения или объекта

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

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

Sub ResizeLegendEntries()
With Worksheets("Sheet1").ChartObjects(1).Activate
      ' Store the current font size
      fntSZ = ActiveChart.Legend.Font.Size
'Temporarily change the font size.
      ActiveChart.Legend.Font.Size = 2
'Place your LegendEntries macro code here to make
         'the changes that you want to the chart legend.
' Restore the font size.
      ActiveChart.Legend.Font.Size = fntSZ
   End With
End Sub

Мы надеемся, что эта статья поможет вам исправить ошибку времени выполнения 1004 в Microsoft Excel. Это руководство дает вам как ручное, так и автоматическое решение, чтобы избавиться от этой ошибки; вы можете использовать любое решение в зависимости от ваших потребностей.

Читать дальше: Клавиши со стрелками не работают в Microsoft Excel.

Ошибка выполнения 1004

 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 1004 Error is a runtime error in VBA. It is also known as application-defined or object-defined error. Why is that? Because we have a limited number of columns in Excel. When our code gives the command to go out of range, we get a 1004 Error. There are other situations when we get this error when we refer to a range that does not exist in the sheet.

VBA Error 1004 in Excel

VBA 1004 Error is a run time error in VBA and occurs while running the code. Errors are part and parcel of the coding, especially when writing for the first time. Therefore, you may come across many errors in VBA. However, this is common for everybody, and there is no big deal about it.

However, knowing the error of why it is coming makes you avoid those mistakes in the coming future.

In this article, we will discuss one of the important errors in Excel, “VBA 1004 Error”.

Table of contents
  • VBA Error 1004 in Excel
    • Top 6 Excel VBA 1004 Runtime Errors
      • #1 – VBA Run Time Error 1004: That Name is already taken. Try a different One:
      • #2 – VBA Run Time Error 1004: Method “Range” of object’ _ Global’ failed:
      • # 3 – VBA Run Time Error 1004: Select Method of Range class failed:
      • #4 – VBA Runtime Error 1004 method open of object workbooks failed:
      • #5 – VBA Runtime Error 1004 method Sorry We couldn’t Find:
      • #6 – VBA Runtime Error 1004 Activate method range class failed:
    • Recommended Articles

VBA 1004 Error

You are free to use this image on your website, templates, etc., Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA 1004 Error (wallstreetmojo.com)

Top 6 Excel VBA 1004 Runtime Errors

You can download this VBA 1004 Error Template here – VBA 1004 Error Template

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

This error occurs while renaming the sheet.

If the worksheet’s name already exists. If you try to assign the same name to another sheet, VBA throws a “Run-time error ‘1004.’ ”

Look at the below code.

Code:

Sub Error1004_Example()

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

End Sub

VBA 1004 Error Example 1

We are trying to rename sheet 2 as sheet 1. But, we already have a sheet named “Sheet1”.

VBA 1004 Error Example 1-2

If we run this code using the F5 key or manually, we will get “Run-time error ‘1004’ “: “That name is already taken. Try a different one.”

VBA 1004 Error Example 1-1

So, try renaming the sheet accordingly.

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

It usually occurs when we try to access the named range in excelName range in Excel is a name given to a range for the future reference. To name a range, first select the range of data and then insert a table to the range, then put a name to the range from the name box on the left-hand side of the window.read more with a spelling mistake or that does not exist you are referring to.

For this, we have named the range of cells “Headings,” as shown in the below image.

VBA 1004 Error Example 2

Now, by using the RANGE object, we can access this range.

Code:

Sub Error1004_Example()

  Range("Headings").Select

End Sub

VBA 1004 Error Example 2-1

If you run this code by pressing the F5 key, then this code will select the named range.

VBA 1004 Error Example 2-2

But, if we mention the named range wrongly, we will get “Run-time error ‘1004.’ “Method “Range” of object’ _ Global” failed.

Code:

Sub Error1004_Example()

  Range("Headngs").Select

End Sub

VBA 1004 Error Example 2-3

Run this code manually or use the F5 key and see the result.

VBA 1004 Error Example 2-4

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

It usually occurs when we try to select the cells other than the active sheet without making the sheet select or active.

 Look at the below code.

Code:

Sub Error1004_Example()

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

End Sub

VBA 1004 Error Example 3

The above code says to select the cells A1 to A5 in the worksheet “Sheet1”. However, to experiment, my present active sheet is “Sheet2”, not “Sheet1”.

We will run this code using the F5 key or manually to see what happens.

VBA 1004 Error Example 3-1

We got “Run-time error ‘1004.’ “Select method of Range class failed” as without activating the sheet; we try to select the cells of that sheet. So first, we need to activate the sheet before we select the cells. Below is the correct code.

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

It usually occurs when you try to open the workbook, which has the same name as the other workbook we have already opened.

Look at the below code.

Code:

Sub Error1004_Example()

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

End Sub

Example 3-2

It will throw the below error.

Example 3-3

#5 – VBA Runtime Error 1004 method Sorry We couldn’t Find:

This error occurs when you try to open the file which does not exist in the mentioned path. For example, it could move, be renamed, or deleted from the mentioned path. One reason for this is the wrong type of path or file name with the excel extensionExcel extensions represent the file format. It helps the user to save different types of excel files in various formats. For instance, .xlsx is used for simple data, and XLSM is used to store the VBA code.read more.

Now, take a look at the below code.

Code:

Sub Error1004_Example()

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

End Sub

Example 4

This code says to open the file “ABC.xlsx” in the mentioned folder path.

We know there is no file in the mentioned folder path. So, we will get the: Run-time error ‘1004’ method when no file exists in the mentioned folder. Sorry, and We couldn’t find it.

Example 4-1

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

This error occurs mainly due to activating the range of cells without activating the worksheet.

Look at the below code.

Code:

Sub Error1004_Example()

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

End Sub

Example 5

This error is similar to the one we have seen in Run-time error’ 1004′: Select method of Range class failed.

If we run manually or use the F5 key, we will get the below error.

Example 5-1

Because without activating the sheet, we cannot activate the cells in it. So first, activate the sheet and then activate the cells of that sheet.

Recommended Articles

This article has been a guide to VBA 1004 Error. Here, we discuss the top 6 types of 1004 run-time errors in VBA and how to fix them, along with examples and downloadable templates. Below are some useful articles related to VBA: –

  • VBA LEN Function
  • VBA Type Mismatch Error
  • VBA Sub Procedures
  • VBA Match Function

VBA 1004 Error

Excel VBA Error 1004

VBA 1004 Error is an error we encounter while we execute a code in VBA it is also known as VBA Runtime error. While we work in VBA or in any other programming language or even in our daily work we encounter different kinds of errors. Sometimes even we miss a single character in the code which causes the whole code not to work or maybe the entire code is wrong.

Errors are definitely a part of the code we write. It may be unintentional but they exist. No matter how pro we are in coding, runtime error can occur anywhere. As explained above VBA 1004 Error is an error which occurs during the runtime of the code in excel. It is also called an application defined or object defined error.

There are different types of reasons we get VBA Runtime Error 1004 in excel, let us learn a few of them.

  • VBA Runtime Error 1004: Method ‘Range’ of object ‘_ Global’ failed:

This error occurs when the range value we refer to VBA is incorrect. It is also called as Method “Range” of object’ _ Global’ failed.

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

We give the same name to a worksheet which is already taken by another worksheet.

  • VBA Runtime Error 1004: Unable to get the select property of Range class:

This is an error when we select a range in another worksheet without activating the worksheet we are referring to.

  • VBA Runtime Error 1004: Method ‘Open’ of object ‘Workbooks’ failed:

This error occurs when we try to open a workbook which is already open or the file is used by another program already.

  • VBA Runtime Error 1004: Sorry We Couldn’t Find:

We get this error when we try to open a worksheet which doesn’t exist.

As we have learned there can be various reasons we get a runtime error. Runtime error can occur at any line of code. We need to learn how to learn to handle these errors and it is called VBA Error Handling.

Example of VBA Runtime Error 1004 in Excel

Now as I have described different types of error which can occur during runtime of any VBA code now let us learn them how they appear with examples.

You can download this VBA 1004 Error Excel Template here – VBA 1004 Error Excel Template

VBA Runtime Error 1004 – Example #1

As explained about this error, this error occurs when we refer to an incorrect named range value in VBA. This can happen if we make a spelling mistake of the named range of to refer a range that doesn’t even exist. To demonstrate this let us make a named range first. I have the following data here.

VBA Error 1004 Example 1

  • Let us name this table header as DATA.

VBA Error 1004 Example 1-1

  • Go to the Developer tab click on Visual Basic to Open VB Editor.

VBA Error 1004 Example 1-2

  • Declare the sub-function to start writing the code.

Code:

Sub Sample()

End Sub

VBA Error 1004 Example 1-3

  • Call the header we named by the following code written below.

Code:

Sub Sample()

Range("Data").Select

End Sub

VBA Error 1004 Example 1-4

  • When we run the code we can see in the excel that it has been selected as we have called the header correctly.

Result of Example 1-4

  • Now we misspell the spelling for the header name.

Code:

Sub Sample()

Range("Dataa").Select

End Sub

VBA Error 1004 Example 1-5

  • Run the code again to see the result.

Result of Example 1-6

We get excel VBA Runtime Error 1004 because we have misspelled the range name.

VBA Runtime Error 1004 – Example #2

We get this error when we try to rename a worksheet with a name which is already taken. For example, I have renamed sheet 1 as “Anand” and I will try to rename sheet 2 as same then see the result.

VBA Error 1004 Example 2

  • Go to the Developer tab click on Visual Basic to Open VB Editor.
  • Declare a sub-function to start writing the code.

Code:

Sub Sample1()

End Sub

VBA Error 1004 Example 2-2

  • Try to rename sheet 2 as Anand by the following code below,

Code:

Sub Sample1()

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

End Sub

VBA Error 1004 Example 2-3

  • Run the above code and see the result.

Result of Example 2

When I try to rename a sheet with the name which is already taken I get an Error.

VBA Runtime Error 1004 – Example #3

I will try to add the value from sheet 2 to a variable in sheet 3. But I will not activate the sheet 2 and see what happens.

  • Go to the Developer tab click on Visual Basic to Open VB Editor.
  • Declare a sub-function to start writing the code.

Code:

Sub Sample2()

End Sub

VBA Error 1004 Example 3-2

  • Declare two variables A and B as an integer.

Code:

Sub Sample2()

Dim A As Integer
Dim B As Integer

End Sub

VBA Error 1004 Example 3-3

  • In Variable B store the value of A in addition to cell A1 of sheet 2.

Code:

Sub Sample2()

Dim A As Integer
Dim B As Integer
B = A + Worksheets("Sheet2").Range("A1").Select

End Sub

VBA Error 1004 Example 3-4

  • Let us suppose the code works and use msgbox function to display the value of B.

Code:

Sub Sample2()

Dim A As Integer
Dim B As Integer
B = A + Worksheets("Sheet2").Range("A1").Select
MsgBox B

End Sub

VBA Error 1004 Example 3-5

  • Run the code to see the result obtained.

Result of Example 3

We get this Error because we have not activated sheet 2 but we are trying to use a value of sheet 2.

VBA Runtime Error 1004 – Example #4

We encounter this runtime error when we have already the same name of workbook open but we try to open it again.

For this example, I have already renamed my workbook as VBA 1004 Error.xlsm and I will try to open it again which is already open and see if I get VBA 1004 Error.

  • Go to the Developer tab click on Visual Basic to Open VB Editor.
  • Declare a sub-function to start writing the code.

Code:

Sub Sample3()

End Sub

VBA Error 1004 Example 4-2

  • Declare a variable as the workbook.

Code:

Sub Sample3()

Dim A As Workbook

End Sub

VBA Error 1004 Example 4-3

Try to open the workbook we have currently already open with the following code.

Code:

Sub Sample3()

Dim A As Workbook

Set wb = Workbooks.Open("\VBA 1004 Error.xlsm", ReadOnly:=True, CorruptLoad:=xlExtractData)

End Sub

VBA Error 1004 Example 4-4

Run the above code to see the result.

Result of Example 4

We get this error because we have already opened the same workbook already.

VBA Runtime Error 1004 – Example #5

We get this error when we try to open a workbook which doesn’t exist. This is somewhat similar to the above error we get as VBA cannot find the workbook.

  • Go to the Developer tab click on Visual Basic to Open VB Editor.
  • Declare a sub-function to start writing the code.

Code:

Sub Sample4()

End Sub

Example 5-1

  • Try Open any workbook with the following code,

Code:

Sub Sample4()

Workbooks.Open Filename:="C:EDUCBA ContentAprilVBA OR Function.xlsm"

End Sub

Example 5-2

  • I have already deleted the sheet from the location.
  • Run the code to see the result.

Result of Example 5-3

As the sheet doesn’t exist at the given location we get this error.

Things to Remember

  • Always check for spelling mistakes.
  • Do not rename multiple worksheets with the same name.
  • Before calling any other reference to be sure to activate the respective worksheet.
  • Before trying to open any other worksheet ensure the path provided is correct.

Recommended Articles

This has been a guide to VBA 1004 Error. Here we discussed Excel VBA Runtime Error 1004 along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA LBound
  2. VBA While Loop
  3. VBA IsError
  4. VBA CLng
 

Возникает при переходе по ссылке из одного листа на другой

 

Сергей

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

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

Юрий я не рунописец но пока начинаю это читать

1004 Ошибка, определенная приложением или объектом. Довольно распространенное универсальное сообщение об ошибке. Данная ошибка возникает тогда, когда ошибка генерируется не в VBA. Другими словами, ошибка определяется в Excel (или в другом объекте) и передается в VBA. Также эта ситуация возникает в случае если ошибка генерируется специально (для этого используется метод Raise объекта Err), но она не определена в VBA

Прикладывайте примеры

Лень двигатель прогресса, доказано!!!

 

Юрий М

Модератор

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

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

Юрий, я подправил название темы: так больше конкретики. Ведь с Вашим названием все вопросы по ошибкам можно смело задавать в Вашей теме. Так лучше? Ну почему бы самому не придумать нормальное название?

 

Сергей

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

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

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

Лень двигатель прогресса, доказано!!!

 

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

 

Юрий М

Модератор

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

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

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

 

Сергей

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

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

#7

16.05.2014 22:53:10

Цитата
Юрий Глодовский пишет: У меня вопрос в какую сторону хотя бы копать.

это не ко мне, сам тупил над такой же ошибкой около 30 минут, грохнул макрос рисую заново, но это чисто развлекуха под пиво к работе у меня ни как не относится

Лень двигатель прогресса, доказано!!!

 

Юрий Глодовский

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

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

#8

16.05.2014 23:42:20

Юрий М, в третьей строке, тот что If Not Intersect…

Код
Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
    '// Проверяем, что выделенная ячейка пересеклась с колонкой "А"
    If Not Intersect(Target, Columns("C")) Is Nothing And Target.Parent.Name = "База" Then
        '//Проверяем, что это не первая строка (там у нас будет заголовок таблицы)
        If Target.Row <> 1 Then
            If Target.Cells.Count = 1 Then '// Если выделена только одна ячейка
                '// Проверяем, что ячейка не пуста
                If Len(Target.Offset(0, -2).Value) <> 0 Then
                    '// На всякий случай - предотвращение ошибок во время файловых операций
                    On Error Resume Next
                    '// Внимание Mkdir (в отличие от DOS-версии) не умеет создавать цепочку папок
                    '// Это означает, что папка, в которой нужно создавать новую, уже должна существовать
                    Dim HomeDir$
                    HomeDir = "D:Base" '// Задаем исходную папку (у Вас - это: "D:Base")
                    MkDir (HomeDir & "" & Target.Offset(0, -2).Value)
                    If Err = 0 Then Cells(Target.Row, "C").Formula = "=HYPERLINK(""" & HomeDir & """&A" & Target.Row & ",""IIIII"")"
                End If
            End If
        End If
    End If
End Sub
 
 

Сергей

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

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

#9

16.05.2014 23:44:38

Цитата
Юрий М пишет: Начните с того, что прогоните код пошагово: для начала выясним — на какой строке и в какой процедуре возникает эта ошибка.

Юрий Глодовский, обращайте внимание на советы, если не знаете как это сделать, спрашивайте, дадут либо ссылку либо совет как это сделать, КОТ хоть и сидит со скелетом но форумчан редко ест

Лень двигатель прогресса, доказано!!!

 

Hugo

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

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

#10

16.05.2014 23:46:23

У меня нет ошибки.
Но попробуйте

Код
    If Not Intersect(Target, ActiveSheet.Columns("C")) Is Nothing And Target.Parent.Name = "База" Then 

кто его знает…
или

Код
    If Not Intersect(Target, target.parent.Columns(3)) Is Nothing And Target.Parent.Name = "База" Then 

Изменено: Hugo17.05.2014 08:31:16

 

Юрий М

Модератор

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

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

Без файла сложно, конечно… Лист «База» есть?

 

Hugo

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

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

Юра, у меня листа База не было. В начале :)
Это не влияет. Нет листа — не выполняется условие всего лишь…

 

Сергей

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

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

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

Лень двигатель прогресса, доказано!!!

 

Юрий Глодовский

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

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

#14

17.05.2014 00:00:16

Цитата
Hugo пишет: If Not Intersect(Target, target.parent.Columns(3)) Is Nothing And Target.Parent.Name = «База» Then

Этот вариант помог. Большое спасибо.
Сергей, посмотрите, может вам пригодится.

 

Юрий М

Модератор

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

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

#15

17.05.2014 00:02:43

Немного смущает несоответствие комментария и строки кода. Комментарий ошибку не вызовет, но всё же:

Код
'// Проверяем, что выделенная ячейка пересеклась с колонкой "А" 

А проверяем столбец С.

 

Сергей

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

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

#16

17.05.2014 00:13:50

Цитата
Юрий Глодовский пишет: может вам пригодится.

в будущем может, на данном моменте эволюции понимания в VBA у меня даже таких строк нет

Лень двигатель прогресса, доказано!!!

 

Казанский

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

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

#17

17.05.2014 01:13:52

Замечу, что Target.Parent это Sh, который передается в процедуру.
Лучше разбить первую проверку на две, чтобы сначала шла быстрая операция сравнения имени, а потом громоздкий Intersect:

Код
If Sh.Name = "База" Then
  If Not Intersect(Target, Sh.Columns(3)) Is Nothing Then 

Понравилась статья? Поделить с друзьями:
  • Ошибка runtime error 1004 excel
  • Ошибка runtime error 1004 application defined or object defined error
  • Ошибка run time error 9 subscript out of range
  • Ошибка rtx voice initialization failed
  • Ошибка rtkvhd64 sys