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.
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 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
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 Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More!
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
2,8765 gold badges31 silver badges45 bronze badges
asked Jul 31, 2013 at 20:58
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.Frank H.
87611 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
21.4k39 gold badges74 silver badges99 bronze badges
answered May 30, 2014 at 4:58
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
Zim84Zim84
3,3842 gold badges34 silver badges40 bronze badges
5
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
EmilyEmily
911 silver badge1 bronze badge
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
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.
answered Mar 29, 2014 at 13:36
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 TimmermanCees Timmerman
17.3k11 gold badges90 silver badges123 bronze badges
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
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
answered Aug 31, 2016 at 13:20
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)
}
answered Mar 20, 2017 at 15:07
I had a similar problem & fixed it applying these steps:
- Unprotecting the sheet that I want to edit
- Changing the range that I had selected by every single cell in the range (exploded)
I hope this will help someone.
batman
1,9372 gold badges22 silver badges41 bronze badges
answered Aug 9, 2016 at 3:50
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
answered Jul 28, 2016 at 14:39
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 CovidiotAndreas Covidiot
4,2085 gold badges50 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
44.5k21 gold badges150 silver badges272 bronze badges
answered May 4, 2016 at 21:27
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
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
SingaravelanSingaravelan
7893 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 PileDave Pile
5,4693 gold badges34 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’mael’
4533 silver badges7 bronze badges
Возникает при переходе по ссылке из одного листа на другой |
|
Сергей Пользователь Сообщений: 11251 |
Юрий я не рунописец но пока начинаю это читать
Прикладывайте примеры Лень двигатель прогресса, доказано!!! |
||
Юрий М Модератор Сообщений: 60757 Контакты см. в профиле |
Юрий, я подправил название темы: так больше конкретики. Ведь с Вашим названием все вопросы по ошибкам можно смело задавать в Вашей теме. Так лучше? Ну почему бы самому не придумать нормальное название? |
Сергей Пользователь Сообщений: 11251 |
Юрий Глодовский, я почему говорю про пример и почему так быстро привел описание ошибки, потому что ща сам сижу втыкаю в неё, так ка записал макрорекодером макрос попытался его усовершенствовать и мне выдает такую фигню и я не думаю что мы с вами делаем одно и тоже Лень двигатель прогресса, доказано!!! |
Сергей, пример приложить не могу, так как там у меня вся рабочая база. Пробовал вынести это дело в отдельный файл, но ошибка не возникает, походу это конфликт макросов. |
|
Юрий М Модератор Сообщений: 60757 Контакты см. в профиле |
Начните с того, что прогоните код пошагово: для начала выясним — на какой строке и в какой процедуре возникает эта ошибка. |
Сергей Пользователь Сообщений: 11251 |
#7 16.05.2014 22:53:10
это не ко мне, сам тупил над такой же ошибкой около 30 минут, грохнул макрос рисую заново, но это чисто развлекуха под пиво к работе у меня ни как не относится Лень двигатель прогресса, доказано!!! |
||
Юрий Глодовский Пользователь Сообщений: 137 |
#8 16.05.2014 23:42:20 Юрий М, в третьей строке, тот что If Not Intersect…
|
||
Сергей Пользователь Сообщений: 11251 |
#9 16.05.2014 23:44:38
Юрий Глодовский, обращайте внимание на советы, если не знаете как это сделать, спрашивайте, дадут либо ссылку либо совет как это сделать, КОТ хоть и сидит со скелетом но форумчан редко ест Лень двигатель прогресса, доказано!!! |
||
Hugo Пользователь Сообщений: 23371 |
#10 16.05.2014 23:46:23 У меня нет ошибки.
кто его знает…
Изменено: Hugo — 17.05.2014 08:31:16 |
||||
Юрий М Модератор Сообщений: 60757 Контакты см. в профиле |
Без файла сложно, конечно… Лист «База» есть? |
Hugo Пользователь Сообщений: 23371 |
Юра, у меня листа База не было. В начале |
Сергей Пользователь Сообщений: 11251 |
вообще не уверен но со своей ошибкой кажись разобрался я когда писал рекодером копировал формулы из одного документа в другой, когда они оба были открыты макрос работал, после того как я закрыл файл из которого копировал формулы начал запускать макрос начала вылетать эта ошибка Лень двигатель прогресса, доказано!!! |
Юрий Глодовский Пользователь Сообщений: 137 |
#14 17.05.2014 00:00:16
Этот вариант помог. Большое спасибо. |
||
Юрий М Модератор Сообщений: 60757 Контакты см. в профиле |
#15 17.05.2014 00:02:43 Немного смущает несоответствие комментария и строки кода. Комментарий ошибку не вызовет, но всё же:
А проверяем столбец С. |
||
Сергей Пользователь Сообщений: 11251 |
#16 17.05.2014 00:13:50
в будущем может, на данном моменте эволюции понимания в VBA у меня даже таких строк нет Лень двигатель прогресса, доказано!!! |
||
Казанский Пользователь Сообщений: 8839 |
#17 17.05.2014 01:13:52 Замечу, что Target.Parent это Sh, который передается в процедуру.
|
||
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.
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:
- Runtime error 1004: Application or object-defined error.
- Runtime error 1004: Method Ranger of Object Worksheet failed.
- 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.
Step 3. Find and enter the Trust Center Settings.
Step 4. Under Macro Settings, tick the option of «Trust access to the VBA project object model.»
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 2003: Choose Excel 97-2003 Template.
Excel 2007 or Later: Choose Excel 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.
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.
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.
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.
- Remove From My Forums
-
Question
-
I try copy column 14 in x to the first column in the new added sheet (MySheet) of y
Sub VBA_Copy_Columns_Workbook()
Dim x As Workbook
Dim y As Workbook
Set x = Workbooks.Open(«C:TempTest.xlsx»)
Set y = ThisWorkbook
x.Worksheets(«Excel_Destination»).ActivateGet error: Excel VBA run-time error 1004 : Application-defined or object-defined error
either run Treat Data:
Range(«N:N»).Select
With Selection
Selection.NumberFormat = «0»
.Value = .Value
End Withor
Copy Data
Application.Intersect(Range(Cells(2, 14), Cells(ActiveSheet.Rows.Count, 14)), ActiveSheet.UsedRange).Copy
y.Activate
Worksheets.Add(After:=Worksheets(1)).Name = «MySheet»
y.Sheets(«MySheet»).Activate
Cells(ActiveSheet.Rows.Count, 1).End(xlUp).Offset(1, 0).Select
ActiveSheet.Paste
Application.CutCopyMode = False»»’Process Completed
MsgBox «Task Completed»
End SubThanks!
-
Edited by
Monday, April 10, 2017 6:16 PM
-
Edited by
Answers
-
Excellent! yes, Column(3) is inserted in this procedure:
Also, I get VERY long sheet: 5 digit number 11789 row. I guess it because :
u.Range(«C7:C» & u.Cells(u.Rows.Count, «B»).End(xlUp).Row).Formula = «=VLOOKUP(B7,MySheet!A:B,2,FALSE)»
B column go down forever. Any Active cell for u.Rows.Count I can use?
That’s okay, Thanks so much!
-
Marked as answer by
Daphne12
Monday, April 17, 2017 4:39 PM -
Edited by
Daphne12
Monday, April 17, 2017 4:45 PM
-
Marked as answer by