Ошибка runtime error 1004 application defined or object defined error

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

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

 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.

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!

В этой статье представлена ошибка с номером Ошибка 1004, известная как Ошибка, определяемая приложением или объектом, описанная как Ошибка времени выполнения «1004». Ошибка, определяемая приложением или объектом.

О программе Runtime Ошибка 1004

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

Определения (Бета)

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

  • Определено — определение — это недвусмысленное утверждение значения слова или фразы.
  • Объект — объект — это любая сущность которыми можно управлять с помощью команд на языке программирования.
  • Время — измерение времени, необходимого для выполнения операции.

Симптомы Ошибка 1004 — Ошибка, определяемая приложением или объектом

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

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

Fix Ошибка, определяемая приложением или объектом (Error Ошибка 1004)
(Только для примера)

Причины Ошибка, определяемая приложением или объектом — Ошибка 1004

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

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

Методы исправления

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

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

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

Метод 2 — Обновите / переустановите конфликтующие программы

Использование панели управления

  • В Windows 7 нажмите кнопку «Пуск», затем нажмите «Панель управления», затем «Удалить программу».
  • В Windows 8 нажмите кнопку «Пуск», затем прокрутите вниз и нажмите «Дополнительные настройки», затем нажмите «Панель управления»> «Удалить программу».
  • Для Windows 10 просто введите «Панель управления» в поле поиска и щелкните результат, затем нажмите «Удалить программу».
  • В разделе «Программы и компоненты» щелкните проблемную программу и нажмите «Обновить» или «Удалить».
  • Если вы выбрали обновление, вам просто нужно будет следовать подсказке, чтобы завершить процесс, однако, если вы выбрали «Удалить», вы будете следовать подсказке, чтобы удалить, а затем повторно загрузить или использовать установочный диск приложения для переустановки. программа.

Использование других методов

  • В Windows 7 список всех установленных программ можно найти, нажав кнопку «Пуск» и наведя указатель мыши на список, отображаемый на вкладке. Вы можете увидеть в этом списке утилиту для удаления программы. Вы можете продолжить и удалить с помощью утилит, доступных на этой вкладке.
  • В Windows 10 вы можете нажать «Пуск», затем «Настройка», а затем — «Приложения».
  • Прокрутите вниз, чтобы увидеть список приложений и функций, установленных на вашем компьютере.
  • Щелкните программу, которая вызывает ошибку времени выполнения, затем вы можете удалить ее или щелкнуть Дополнительные параметры, чтобы сбросить приложение.

Метод 1 — Закройте конфликтующие программы

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

  • Откройте диспетчер задач, одновременно нажав Ctrl-Alt-Del. Это позволит вам увидеть список запущенных в данный момент программ.
  • Перейдите на вкладку «Процессы» и остановите программы одну за другой, выделив каждую программу и нажав кнопку «Завершить процесс».
  • Вам нужно будет следить за тем, будет ли сообщение об ошибке появляться каждый раз при остановке процесса.
  • Как только вы определите, какая программа вызывает ошибку, вы можете перейти к следующему этапу устранения неполадок, переустановив приложение.

Метод 3 — Обновите программу защиты от вирусов или загрузите и установите последнюю версию Центра обновления Windows.

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

Метод 4 — Переустановите библиотеки времени выполнения

Вы можете получить сообщение об ошибке из-за обновления, такого как пакет MS Visual C ++, который может быть установлен неправильно или полностью. Что вы можете сделать, так это удалить текущий пакет и установить новую копию.

  • Удалите пакет, выбрав «Программы и компоненты», найдите и выделите распространяемый пакет Microsoft Visual C ++.
  • Нажмите «Удалить» в верхней части списка и, когда это будет сделано, перезагрузите компьютер.
  • Загрузите последний распространяемый пакет от Microsoft и установите его.

Метод 5 — Запустить очистку диска

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

  • Вам следует подумать о резервном копировании файлов и освобождении места на жестком диске.
  • Вы также можете очистить кеш и перезагрузить компьютер.
  • Вы также можете запустить очистку диска, открыть окно проводника и щелкнуть правой кнопкой мыши по основному каталогу (обычно это C :)
  • Щелкните «Свойства», а затем — «Очистка диска».

Метод 6 — Переустановите графический драйвер

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

  • Откройте диспетчер устройств и найдите драйвер видеокарты.
  • Щелкните правой кнопкой мыши драйвер видеокарты, затем нажмите «Удалить», затем перезагрузите компьютер.

Метод 7 — Ошибка выполнения, связанная с IE

Если полученная ошибка связана с Internet Explorer, вы можете сделать следующее:

  1. Сбросьте настройки браузера.
    • В Windows 7 вы можете нажать «Пуск», перейти в «Панель управления» и нажать «Свойства обозревателя» слева. Затем вы можете перейти на вкладку «Дополнительно» и нажать кнопку «Сброс».
    • Для Windows 8 и 10 вы можете нажать «Поиск» и ввести «Свойства обозревателя», затем перейти на вкладку «Дополнительно» и нажать «Сброс».
  2. Отключить отладку скриптов и уведомления об ошибках.
    • В том же окне «Свойства обозревателя» можно перейти на вкладку «Дополнительно» и найти пункт «Отключить отладку сценария».
    • Установите флажок в переключателе.
    • Одновременно снимите флажок «Отображать уведомление о каждой ошибке сценария», затем нажмите «Применить» и «ОК», затем перезагрузите компьютер.

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

Другие языки:

How to fix Error 1004 (Application-defined or object-defined error) — Run-time error ‘1004’. Application-defined or object-defined error.
Wie beheben Fehler 1004 (Anwendungsdefinierter oder objektdefinierter Fehler) — Laufzeitfehler ‘1004’. Anwendungsdefinierter oder objektdefinierter Fehler.
Come fissare Errore 1004 (Errore definito dall’applicazione o dall’oggetto) — Errore di runtime ‘1004’. Errore definito dall’applicazione o dall’oggetto.
Hoe maak je Fout 1004 (Toepassingsgedefinieerde of objectgedefinieerde fout) — Runtime-fout ‘1004’. Door een toepassing gedefinieerde of door een object gedefinieerde fout.
Comment réparer Erreur 1004 (Erreur définie par l’application ou par l’objet) — Erreur d’exécution ‘1004’. Erreur définie par l’application ou par l’objet.
어떻게 고치는 지 오류 1004 (응용 프로그램 정의 또는 개체 정의 오류) — 런타임 오류 ‘1004’. 응용 프로그램 정의 또는 개체 정의 오류입니다.
Como corrigir o Erro 1004 (Erro definido pelo aplicativo ou definido pelo objeto) — Erro em tempo de execução ‘1004’. Erro definido pelo aplicativo ou definido pelo objeto.
Hur man åtgärdar Fel 1004 (Programdefinierat eller objektdefinierat fel) — Körtidsfel ‘1004’. Programdefinierat eller objektdefinierat fel.
Jak naprawić Błąd 1004 (Błąd zdefiniowany przez aplikację lub zdefiniowany przez obiekt) — Błąd wykonania „1004”. Błąd zdefiniowany przez aplikację lub obiekt.
Cómo arreglar Error 1004 (Error definido por la aplicación o definido por el objeto) — Error en tiempo de ejecución ‘1004’. Error definido por la aplicación o por el objeto.

The Author Об авторе: Фил Харт является участником сообщества Microsoft с 2010 года. С текущим количеством баллов более 100 000 он внес более 3000 ответов на форумах Microsoft Support и создал почти 200 новых справочных статей в Technet Wiki.

Следуйте за нами: Facebook Youtube Twitter

Последнее обновление:

17/01/23 08:03 : Пользователь Windows 10 проголосовал за то, что метод восстановления 2 работает для него.

Рекомендуемый инструмент для ремонта:

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

ШАГ 1:

Нажмите здесь, чтобы скачать и установите средство восстановления Windows.

ШАГ 2:

Нажмите на Start Scan и позвольте ему проанализировать ваше устройство.

ШАГ 3:

Нажмите на Repair All, чтобы устранить все обнаруженные проблемы.

СКАЧАТЬ СЕЙЧАС

Совместимость

Требования

1 Ghz CPU, 512 MB RAM, 40 GB HDD
Эта загрузка предлагает неограниченное бесплатное сканирование ПК с Windows. Полное восстановление системы начинается от $19,95.

ID статьи: ACX02492RU

Применяется к: Windows 10, Windows 8.1, Windows 7, Windows Vista, Windows XP, Windows 2000

Icon Ex Номер ошибки: Ошибка 1004
Название ошибки: Application-defined or object-defined error
Описание ошибки: Run-time error ‘1004’. Application-defined or object-defined error.
Разработчик: Microsoft Corporation
Программное обеспечение: Microsoft Excel
Относится к: Windows XP, Vista, 7, 8, 10, 11

Проверка «Application-defined or object-defined error»

Обычно люди ссылаются на «Application-defined or object-defined error» как на ошибку времени выполнения (ошибку). Чтобы убедиться, что функциональность и операции работают в пригодном для использования состоянии, разработчики программного обеспечения, такие как Microsoft Corporation, выполняют отладку перед выпусками программного обеспечения. Ошибки, такие как ошибка 1004, иногда удаляются из отчетов, оставляя проблему остается нерешенной в программном обеспечении.

Пользователи Microsoft Excel могут столкнуться с ошибкой 1004, вызванной нормальным использованием приложения, которое также может читать как «Run-time error ‘1004’. Application-defined or object-defined error.». Сообщение об этой ошибке 1004 позволит разработчикам обновить свое приложение и исправить любые ошибки, которые могут вызвать его. Затем Microsoft Corporation исправит ошибки и подготовит файл обновления для загрузки. Следовательно, разработчик будет использовать пакет обновления Microsoft Excel для устранения ошибки 1004 и любых других сообщений об ошибках.

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

В первый раз, когда вы можете столкнуться с ошибкой среды выполнения Microsoft Excel обычно с «Application-defined or object-defined error» при запуске программы. Вот три наиболее заметные причины ошибки ошибки 1004 во время выполнения происходят:

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

Утечка памяти «Application-defined or object-defined error» — Когда Microsoft Excel обнаруживает утечку памяти, операционная система постепенно работает медленно, поскольку она истощает системные ресурсы. Возможные искры включают сбой освобождения, который произошел в программе, отличной от C ++, когда поврежденный код сборки неправильно выполняет бесконечный цикл.

Ошибка 1004 Logic Error — логическая ошибка Microsoft Excel возникает, когда она производит неправильный вывод, несмотря на то, что пользователь предоставляет правильный ввод. Когда точность исходного кода Microsoft Corporation низкая, он обычно становится источником ошибок.

Как правило, такие Microsoft Corporation ошибки возникают из-за повреждённых или отсутствующих файлов Application-defined or object-defined error, а иногда — в результате заражения вредоносным ПО в настоящем или прошлом, что оказало влияние на Microsoft Excel. Основной способ решить эти проблемы вручную — заменить файл Microsoft Corporation новой копией. Запуск сканирования реестра после замены файла, из-за которого возникает проблема, позволит очистить все недействительные файлы Application-defined or object-defined error, расширения файлов или другие ссылки на файлы, которые могли быть повреждены в результате заражения вредоносным ПО.

Распространенные проблемы Application-defined or object-defined error

Наиболее распространенные ошибки Application-defined or object-defined error, которые могут возникнуть на компьютере под управлением Windows, перечислены ниже:

  • «Ошибка Application-defined or object-defined error. «
  • «Недопустимая программа Win32: Application-defined or object-defined error»
  • «Извините за неудобства — Application-defined or object-defined error имеет проблему. «
  • «К сожалению, мы не можем найти Application-defined or object-defined error. «
  • «Application-defined or object-defined error не может быть найден. «
  • «Ошибка запуска программы: Application-defined or object-defined error.»
  • «Application-defined or object-defined error не выполняется. «
  • «Application-defined or object-defined error остановлен. «
  • «Неверный путь к программе: Application-defined or object-defined error. «

Эти сообщения об ошибках Microsoft Corporation могут появляться во время установки программы, в то время как программа, связанная с Application-defined or object-defined error (например, Microsoft Excel) работает, во время запуска или завершения работы Windows, или даже во время установки операционной системы Windows. Документирование проблем Application-defined or object-defined error в Microsoft Excel является ключевым для определения причины проблем с электронной Windows и сообщения о них в Microsoft Corporation.

Причины проблем Application-defined or object-defined error

Проблемы Application-defined or object-defined error вызваны поврежденным или отсутствующим Application-defined or object-defined error, недопустимыми ключами реестра, связанными с Microsoft Excel, или вредоносным ПО.

В частности, проблемы Application-defined or object-defined error возникают через:

  • Недопустимая или поврежденная запись Application-defined or object-defined error.
  • Вредоносные программы заразили Application-defined or object-defined error, создавая повреждение.
  • Application-defined or object-defined error злонамеренно или ошибочно удален другим программным обеспечением (кроме Microsoft Excel).
  • Другая программа находится в конфликте с Microsoft Excel и его общими файлами ссылок.
  • Поврежденная загрузка или неполная установка программного обеспечения Microsoft Excel.

Продукт Solvusoft

Загрузка
WinThruster 2022 — Проверьте свой компьютер на наличие ошибок.

Совместима с Windows 2000, XP, Vista, 7, 8, 10 и 11

Установить необязательные продукты — WinThruster (Solvusoft) | Лицензия | Политика защиты личных сведений | Условия | Удаление

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

This is one of the most common run-time errors. By the end of this article, you will understand why that is and how to fix it. A run-time error is the type of error that occurs during the execution of the code. VBA does not know about it prior to actually running the code. There are different variations of this error; we will provide an example of each of the types below.

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

When a range reference is not correct. It could be incorrect because it’s misspelled. It could also be incorrect because it’s trying to get a range that is at an impossible value, such as row 0 or row -2. In the example below, we’re referring to row zero and we’re using the wrong syntax. VBA recognizes that we’re trying to refer to a range but it sees that the arguments (parameters) written within the range in order to identify it are written incorrectly; there should be no commas when using Range().

Sub Range_Error()
Range(0, 1).Select
End Sub

range of object global failed

Instead, we should write the code as follows:

Sub Range_Error()
Range(“A1”).Select
End Sub

We could also run into this problem unintentionally if we are looping a variable, such as X, and it becomes zero.

In the below example, X is equal to 5 and the loop is set to keep reducing X by 1 until it reaches -1 then it would not execute. But an error will occur when X = 0.

I set the code to write ‘Correct’ in each of the cells up until the cell we are not able to insert values into. Our code will insert ‘Correct’ in Range(“A5) to Range(“A1”) then will give the error when we ask it to insert ‘Correct’ into Range(“A0”).

Note that we didn’t define X to be a String, so VBA assumes it’s a variant. This means it can be any type of data, so Excel assumes that it’s the type of data that should be utilized in the context we’re utilizing it in. In this case, X would be considered a string. But when X is zero, Excel doesn’t know that it should be string, since “A0” doesn’t exist as a range. So it treats the zero as a number, which triggers this error, because it’s syntax related, meaning what’s written inside Range() is not written correctly from a syntax point of view.

Sub Range_Error()
X = 5
Do Until X = -1
Range("A" &amp;amp;amp; X) = "Correct"
X = X - 1
Loop
End Sub

method range of object global failed

To correct the problem, we need to stop our code from running the loop once X reaches 0.

Sub Range_Error()
X = 5
Do Until X = 0
Range("A" &amp;amp;amp; X) = "Correct"
X = X - 1
Loop
End Sub

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

This error is shown when we are trying to give the same name to a worksheet which has already been given to another worksheet in the same workbook. Given that we already have a sheet named “Sheet1”, we create a new sheet, we click on it so that it becomes the active sheet, and we try to name it “Sheet1” by running the below code. We get an error immediately once we reach the sheet name changing line.

Sub Error_Name_Taken()
ThisWorkbook.Sheets("Sheet2").Activate
ActiveSheet.Name = "Sheet1"
End Sub

name already taken

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

This error occurs when we attempt to activate a range through VBA in another worksheet (not the currently active one) without activating that worksheet first.

Sub Error_Select_Failed()
ThisWorkbook.Sheets("Sheet2").Activate
ThisWorkbook.Sheets("Sheet1").Range("A1").Select
End Sub

select method of range class failed

To correct the issue, we would need to first activate “Sheet1” first before attempting to select a range inside of it. Adding a line to active the worksheet resolves the issue.

Sub Error_Select_Failed()
ThisWorkbook.Sheets("Sheet2").Activate
ThisWorkbook.Sheets("Sheet1").Activate
ThisWorkbook.Sheets("Sheet1").Range("A1").Select
End Sub

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

This error occurs when we use VBA to open a workbook that cannot be opened. The reason that Excel is unable to open the workbook could be because it is already open, or the workbook is being used by another program at that moment. A special case exists when you attempt to open a file in read-only mode while the file is corrupt. This would give an error because Excel can open a corrupt file only if it is allowed to repair it first, which it does by writing to it. So, if you open a corrupt file in read-only mode, you are essentially preventing it from repairing the file and hence it would fail to open.

EXAMPLE 5: VBA Runtime Error 1004: file format is not valid

This error, like the one in example 5, is related to attempting to open a file. In this situation, however, we are trying to open a file that isn’t an Excel file; the file doesn’t have any of the Excel extensions ( .xlsx, .xls, .xlsb, .xlsm, etc.)

Sub error_workbook_open()
Workbooks.Open "C:UsersmmostDropboxDaniel TrohaRun-time error 1004.docx"
End Sub

file format is not valid

The code is attempting to open a word document file with extension .docx. Using ‘Workbooks.Open’ can only be used for files that have Excel extensions. To open documents of different extensions, we will need to take a completely different approach. For example, the below code opens a word document.

Sub error_word_doc_open()
Dim wordapp
Dim strFileName As String
strFileName = "C:UsersmmostDropbox Else Without If.docx"
Set wordapp = CreateObject("word.Application")
wordapp.Documents.Open strFile
wordapp.Visible = True
End Sub

EXAMPLE 6: VBA Runtime Error 1004: Sorry We Couldn’t Find:

This error occurs whenever we are trying to open a file that does not exist at the specified path. When faced with this error, it’s important to check three aspects of the file path; file location, file name, and file extension. Any of these parameters could be wrong, so check each of them carefully.

Sub error_workbook_open()
Workbooks.Open "C:UsersmmostDropboxAnother Workbook.xls"
End Sub

couldn't find workbook

EXAMPLE 7: VBA Runtime Error 1004: Application-defined or Object-defined error

This error encompasses a wide range of possibilities. The error is triggered due to violating one of the rules that are used to handle the object you’re working with.

For example, in the following code, I try to select a cell that exists on row -1 and column 1. There is no such cell as the minimum row number allowed is 1, thus, VBA determines that I violated this rule and throws this error.

Note that this is different from Example 1 in that the syntax I am using here is perfectly correct, but I am violating particular rules that once violated, trigger an error. The wide range of these rules make this one of the most common errors in VBA. To resolve it, you will want to know more about the object you’re working with (in this case it’s a cell in the worksheet) and understand the rules and limitations that exist on the various values that you can use with the object.

Sub error_object_defined()
ThisWorkbook.Sheets(1).Cells(-1, 1).Select
End Sub

application defined or object defined error

To wrap it up, here’s one example of where a syntax error calling a function causes this error to occur.

Contents

  • What Is the Runtime Error 1004 In Excel?
  • Why Am I Getting the Excel Runtime Error 1004?
  • How to Fix the Runtime Error 1004 in Excel on Windows 10
    • The following solutions have been proven to work:
    • Fix 1: Run an Antimalware Scan
    • Fix 2: Allow Access to the VBA Project Object Model
    • Fix 3: Create a New Excel Template
    • Fix 4: Uninstall Microsoft Works
    • Fix 5: Remove GWXL97.XLA
  • Conclusion

What causes the Runtime Error 1004 message on Microsoft Excel?

Are you searching for how to fix ‘Cannot run the macro’ in Excel? Then you’ve come to the right place. The message is one of many that may appear as a result of Runtime Error 1004. Other variations of the Excel Error 1004 include:

  • Application-defined or object-defined error: Runtime Error 1004
  • Method ‘Ranger’ of Object Worksheet Failed
  • Copy method of worksheet class failed
  • Programmatic access to Visual Basic Project is not trusted
  • Excel macro “Run-time error 1004″
  • Method open of object workbooks failed: Runtime Error 1004
  • Select method of Range class failed: Excel VBA Runtime Error 1004
  • Application-defined or object-defined error: Save As VBA Run Time Error 1004
  • Method range of object _global failed visual basic: Runtime Error 1004

What Is the Runtime Error 1004 In Excel?

Microsoft Excel is a useful and highly demanded spreadsheet that makes data computation easy. It is used by both individuals and businesses all over the world and comes in XLS and XLSX format.

However, while working on an Excel file or trying to generate a Macro, many users have been aggravated by the Runtime Error 1004. It prevents you from making any changes in your Excel workbook, makes you unable to use certain resource libraries, and freezes or crashes the program or even your system. It causes annoying performance problems while working with Visual Basic applications.

The Runtime Error 1004 can occur on any version of Excel: from Excel 2003 to Excel 2019. It mostly appears when you try running Microsoft Visual Basic for Applications Macro. The problem is due to a security procedure that is meant to lock Microsoft VBA from Excel. The Runtime Error 1004 likely won’t occur if you grant security access. The error could also be due to program corruption as a result of malware infection.

Why Am I Getting the Excel Runtime Error 1004?

The Runtime Error 1004 can appear as a result of:

  1. Corrupt MS Excel desktop shortcut.
  2. Copying and pasting filtered data into an MS Office Excel workbook.
  3. Program conflict while opening the VBA Excel file.
  4. Programmatically setting a range of values with a collection of large string.
  5. Application or object-defined error.

Whatever the reason may be, the issue is easy to get rid of. Keep reading to learn how to fix the Runtime Error 1004 when you make changes in Excel.

How to Fix the Runtime Error 1004 in Excel on Windows 10

The following solutions have been proven to work:

  1. Run an antimalware scan
  2. Allow Access to the VBA Project Object Model
  3. Create a new Excel template
  4. Uninstall Microsoft Works
  5. Remove GWXL97.XLA

By the time you have tried one or a few of the above fixes, the error will be resolved. We will now provide you with detailed steps to carry out the solutions.

Fix 1: Run an Antimalware Scan

This is the first fix you should try once you get the Runtime Error 1004. If your system is infected with viruses and other types of malware, you will run into unpleasant and unexpected issues. Your system and application will malfunction. Moreover, important files and documents get corrupted.

Run a full system scan with a strong antivirus program. We recommend you use Auslogics Anti-Malware. The tool has precision tools to detect and eliminate even the most elusive malicious elements that your existing antivirus program may miss. Auslogics is a Microsoft partner. They are a certified Microsoft Silver Application developer. Auslogics products have been tested and trusted by experts and millions of users worldwide.

Fix 2: Allow Access to the VBA Project Object Model

The procedure for this solution is easy. Follow the steps below:

  1. Launch Excel and click on the File tab.
  2. Click on Options.
  3. Click on Trust Center. It is the last option in the left pane.
  4. Click the Trust Center Settings button in the right pane.
  5. In the new page that opens, locate Macro Settings in the left pane and click on it.
  6. Mark the checkbox for ‘Trust access to the VBA project object model’ under the Developer Macro Settings section in the right pane.
  7. Click the OK button.

Fix 3: Create a New Excel Template

Rather than copy or duplicate your existing worksheet, you can put your new Excel Worksheet file within a template. This will help fix the Runtime Error 1004. Here’s how to get it done:

  1. Launch Excel.
  2. Press the Ctrl + N combination on your keyboard to open a new workbook. Make sure to leave only one sheet on the workbook. Delete the rest.
  3. Modify the workbook to suit your needs.
  4. Save the workbook by pressing Ctrl + S on your keyboard. Or if you use Excel 2003, click on the File tab and click Save as. For Excel 2007 and newer versions, click the Microsoft Office icon in the top-left corner of your screen and then click on Save as.
  5. Choose a location to save the file on your computer and enter a name for the file.
  6. Click the drop-down arrow beside ‘Save as type’ and select Excel Template (.xlt) if you are using Excel 2003. If you are using Excel 2007 and later versions, select Excel Template (.xltx) instead.
  7. After saving the template, use the following code to insert it:

Add Type:=pathfilename

Make sure to replace “pathfilename” with the actual path and file name of the template.

Fix 4: Uninstall Microsoft Works

Here’s the procedure to follow:

  1. Right-click on the Start button to open the Power User menu. Select Task Manager from the list. Alternatively, press the Ctrl + Alt + Del combination on your keyboard and then click on Task Manager.
  2. Once in Task Manager, click on each of the running apps and click the End Task button.
  3. Close the Task Manager window.
  4. Open the Run utility by pressing the Windows + R keyboard combination. Type “appwiz.cpl” (no quotes) into the text field and click the OK button or press Enter on your keyboard.
  5. Locate Microsoft Works in the list of apps and right-click on it. Then, click on Uninstall from the context menu. Confirm the action if prompted.

Fix 5: Remove GWXL97.XLA

Here’s how to delete the GWXL97.XLA file:

  1. Press the Windows + E combination on your keyboard to open File Explorer.
  2. Navigate this path: C: Users > User > Name > AppData > Local> MicrosoftExcel.
  3. Open the XLStart folder.
  4. Locate and delete the GWXL97.aXLA file.

Conclusion

We hope the solutions provided above have helped you to successfully fix the Runtime Error 1004 in Microsoft Excel and recover the data on your file. There are many issues that can lead to the runtime error. However, by the time you get to the end of this guide, you will be just fine.

Don’t hesitate to leave your questions or comments in the section below. We love hearing from you.

Do you like this post? 🙂

Please rate and share it and subscribe to our newsletter!


5 votes,


average: 5.00 out of
5

loadingLoading…

Понравилась статья? Поделить с друзьями:
  • Ошибка rtx voice initialization failed
  • Ошибка rtkvhd64 sys
  • Ошибка rt n11p
  • Ошибка rpm bobcat
  • Ошибка rpgvxace rtp is required to run this game что делать