Майкрософт Эксель — одна из самых популярных электронных таблиц, используемых во всем мире как для личных, так и для деловых целей. Это универсальное место для хранения, организации и обработки данных организованным способом. MS Excel поставляется в основном с двумя расширениями, то есть в формате XLS и XLSX. Однако, помимо невероятной популярности, ошибки во время выполнения — обычная неприятность для очень многих пользователей Windows, и одной из самых распространенных является ошибка. Ошибка выполнения 1004.
В этом руководстве мы собираемся обсудить эту распространенную ошибку времени выполнения 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. Вы можете использовать любой из следующих методов, чтобы решить проблему.
- Создать новый шаблон Excel
- Запустите сканирование на вирусы
- Для VB: ошибка времени выполнения ‘1004’, измените размер записей легенды
Давайте подробно рассмотрим каждый из этих методов.
1]Создайте новый шаблон Excel
В некоторых случаях для устранения этой проблемы достаточно просто вставить новый лист из шаблона вместо создания копии существующего листа. Вот что вам нужно сделать:
1]Откройте MS Excel в вашей системе
2]Нажмите ‘CTRL + N‘для создания нового листа Microsoft Excel или просто выберите’Пустая книга‘с первого экрана.
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.
-
#2
You cannot Unprotect Sheets via VBA code on a shared workbook. Sorry, no way around that.
But instead of standard protection, you could modify your code to protect (while it’s NOT shared) to use UserInterfaceOnly…
So UNShare the book..
Then remove any code in your book that Protects/unprotects sheets…
run a macro to protect all sheets you want protected using UserInterfaceOnly = TRUE
Sheets(«Sheet1″).Protect Password:=»PasswordHere», UserInterfaceOnly:=True
Then reshare the workbook.
Now your VBA code can modify sheets, but users can’t
-
#3
I had posted an idea, then saw JonMo1’s post,
You cannot Unprotect Sheets via VBA code on a shared workbook.
Go figure. I Love how we just aren’t allowed to do certain things. Good to know Jon, thanks. I know thats going to come up at ym office eventually.
Jason
-
#4
That’s a no go.
My code now looks like this:
Option Explicit
Public oldRange As Range
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim cmtText As String
Cancel = True
Sheets(«Sheet1»).UnProtect Password:=»Thermo544″, UserInterfaceOnly:=True
cmtText = InputBox(«Enter Comment»)
If cmtText = «» Then
Sheets(«Sheet1″).Protect Password:=»Thermo544», UserInterfaceOnly:=True
Exit Sub
End If
Target.ClearComments
Target.AddComment
Target.Comment.Text Text:=cmtText
Sheets(«Sheet1″).Protect Password:=»Thermo544», UserInterfaceOnly:=True
End Sub
The run-time error 1004 now states: «Application-defined or object-defined error.»
Additionally, when I replace the word highlighted in red with «Protect» the run-time 1004 error says: «The cell or chart you are trying to change is protected and therefore read-only. To modify a protected cell or chart, first remove protection using the Unprotect Sheet command (Tools menu, Protection submenu). You may be prompted for a password.»
I am not sure if this is exactly what you were suggesting I do. I will try to ponder some other ideas to see if I can make it work.
Thanks
-
#5
I just wrote this very simple test in a new workbook I made up:
Code:
Option Explicit
Sub lockit()
Sheets("sheet1").Protect Password:="abc123"
End Sub
Sub unlockit()
Sheets("sheet1").Unprotect Password:="abc123"
End Sub
It works just fine. Remeber what Jon wrote just before me…
You cannot Unprotect Sheets via VBA code on a shared workbook.
That might be your entire problem.
Jason
update:
I forgot to add the userinterface part. That is only required on the protecting, not the unprotecting I believe. I got an error when trying to unprotect with that argument on, but not without it.
-
#6
<!— / icon and title —><!— message —>
That’s a no go.
My code now looks like this:
Option Explicit
Public oldRange As RangePrivate Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim cmtText As String
Cancel = True
Sheets(«Sheet1»).UnProtect Password:=»Thermo544″, UserInterfaceOnly:=True
cmtText = InputBox(«Enter Comment»)
If cmtText = «» Then
Sheets(«Sheet1″).Protect Password:=»Thermo544», UserInterfaceOnly:=True
Exit Sub
End If
Target.ClearComments
Target.AddComment
Target.Comment.Text Text:=cmtText
Sheets(«Sheet1″).Protect Password:=»Thermo544», UserInterfaceOnly:=True
End SubThe run-time error 1004 now states: «Application-defined or object-defined error.»
REMOVE ALL CODE THAT PROTECTS or UNPROTECTS SHEETS. — and DON’T put it back.
UnShare your book.
Ran a macro that protects sheets using UserInterfaceOnly = TRUE.
You will only need to Run that macro once.
Reshare your book.
You will no longer need to unprotect/reprotect your sheets in VBA.
Your sheets will be protected from users modifying them, but VBA code WILL be able to modify sheets WITHOUT needing to UNprotect them.
Last edited: Feb 22, 2008
-
#8
You are right Jax, apparently there’s nothing you can do.
Once you save / close / reopen the workbook, the UserInterFace = TRUE is lost…
And you CAN’T run a macro to ReSet it when the book is shared…You would have to UNshare it, run the code to set the userinterfaceonly, then reshare the book.
And No, you can’t use code to UNshare the book either. I tried….
This is one reason most people don’t like using shared workbooks…
There are lots of things you can’t do to a shared workbook, it sucks…
You might consider using ACCESS for your users to enter data into then.
-
#9
Yes..I thought I was going to pull my hair out trying to get your code to work. It does suck and Access sounds like a much better option.
Thanks to you both for your help
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:
- Download Excel File Repair Tool rated Excellent by Softpedia, Softonic & CNET.
- Select the corrupt Excel file (XLS, XLSX) & click Repair to initiate the repair process.
- 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:
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
The lists of error messages associated with this Excel error 1004 are:
- VB: run-time error ‘1004’: Application-defined or object-defined error
- Excel VBA Runtime error 1004 “Select method of Range class failed”
- runtime error 1004 method range of object _global failed visual basic
- Excel macro “Run-time error ‘1004″
- Runtime error 1004 method open of object workbooks failed
- Run time error ‘1004’: Method ‘Ranger’ of Object’ Worksheet’ Failed
- 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.”
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.
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.
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.
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.
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.
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:
- Due to corruption in the desktop icon for MS Excel.
- Conflict with other programs while opening VBA Excel file.
- When filtered data is copied and then pasted into MS Office Excel workbook.
- Due to application or object-defined error.
- 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.
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.
3. Next, in the Control Panel select Add or Remove Program.
4. Here, you will get the list of programs that are currently installed on your PC, and then from the list select Microsoft Work.
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
OR Excel 2007 or latest versions: Tap to the Microsoft Office button after then hit the Save As option.
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)
- And Excel 2007 or later version have to choose the Excel Template (.xltx)
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.
3. Then open the following directory – C:Program FilesMSOfficeOfficeXLSTART
4. Here you need to delete “GWXL97.XLA” file
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.
Ошибка выполнения Excel 1004 обычно возникает, когда вы работаете с поврежденным документом. Вы также получаете эту ошибку, если открываете файл VBA Excel, когда ваш Excel конфликтует с другими программами.
Ошибка выполнения Excel 1004 может появиться из-за множества других основных проблем. Наиболее распространенные сообщения об ошибках включают следующее:
VB: ошибка времени выполнения «1004»: ошибка, определяемая приложением или объектом
Ошибка выполнения Excel VBA 1004 «Не удалось выбрать метод класса Range»
ошибка выполнения 1004 диапазон методов объекта _global не удалось Visual Basic
Макрос Excel «Ошибка выполнения ‘1004″
Ошибка выполнения 1004. Не удалось открыть книгу объектов.
Ошибка времени выполнения «1004»: сбой метода «Рейнджер» рабочего листа объекта
Сохранить как ошибка времени выполнения VBA 1004: ошибка, определяемая приложением или объектом
Если вы получите какую-либо из этих ошибок, вы можете исправить ошибку, используя решения здесь.
Что такое ошибка времени выполнения 1004 в Excel?
Ошибка времени выполнения характерна для приложений, которые интегрируют сценарий Microsoft Visual Basic для приложений (также известный как VBA) для выполнения повторяющихся задач.
Все приложения Microsoft Office используют это специфичное для Windows программирование, но наиболее распространенные проблемы возникают в Excel, особенно в Excel 2007.
Многие пользователи сообщают о проблемах при создании макросов. Макрос — это функция Excel, которая записывает нажатия клавиш и клики, чтобы помочь вам автоматизировать повторяющиеся задачи.
Часто эта задача конфликтует с VBA, что приводит к ошибке 1004. Другой распространенной причиной является поврежденное приложение Excel или поврежденный файл XLS.
Другие возможные причины, связанные с этой ошибкой, включают количество записей легенды, превышающее доступное пространство, и конфликт файлов между Excel и другими приложениями.
Хорошей новостью является то, что эта ошибка существует уже некоторое время, и есть несколько проверенных методов, которые помогут вам ее исправить.
Как исправить ошибку выполнения 1004 в Excel?
1. Удалите Microsoft Works
- Нажмите комбинацию CTRL + ALT + DEL и нажмите «Диспетчер задач».
- Закройте все программы, которые открыты в данный момент.
- Затем нажмите Windows + R, чтобы открыть утилиту «Выполнить».
- Здесь введите appwiz.cpl и нажмите кнопку ОК.
- В списке программ, установленных на вашем компьютере, найдите Microsoft Works. Щелкните его правой кнопкой мыши и нажмите « Удалить».
2. Создайте еще один шаблон Excel
- Запустите Microsoft Excel на своем компьютере.
- Затем создайте новую книгу Microsoft Excel, нажав комбинацию CTRL + N или выбрав Пустая книга на первом экране.
- После создания рабочей книги удалите все листы в рабочей книге, кроме одного.
- Отформатируйте эту книгу, которую вы сохранили.
- Вы можете изменить эту книгу в соответствии с вашими потребностями.
- Наконец, выберите «Файл» > «Сохранить как», чтобы сохранить файл в формате шаблона Excel (.xltx или. xlt).
- Используйте этот формат для Excel в 2017 году и выше.
- Когда документ успешно сохранен, вы можете вставить шаблон с помощью этого кода:
Add Type:=pathfilename
Не забудьте заменить имя файла на фактическое имя документа.
3. Удалите GWXL97.XLA.
- Начните с открытия проводника на вашем компьютере.
- Вы можете сделать это, нажав Windows + E.
- Затем щелкните адресную строку, введите следующий путь
C:/Users/user name/AppData/Local/Microsoft Excel
и нажмите Enter:
- Здесь откройте папку XLStart.
- Наконец, найдите файл GWXL97.XLA и удалите его.
Зная, что существует множество причин ошибки времени выполнения 1004 в Excel, может сработать только одно решение. С помощью этого руководства теперь вы можете исправить ошибку времени выполнения Microsoft Excel 1004 и восстановить данные файла.
Honey Пользователь Сообщений: 204 |
Всем доброго времени суток! Столкнулась с такой вот проблемой: ошибка 1004 Method visible of object worksheet failed выходит при открытии файла только на одном компьютере. Этот же файл на других компьютерах работает также. Везде стоит офис 2016. Надстройки и параметры макросов одинаковые. В чем может быть причина? Причем даже кнопка debug не нажимается, чтобы посмотреть где конкретно сидит причина ошибки… Заранее благодарю всех на любые ответы! |
Irbis_evs Пользователь Сообщений: 337 |
пример приложите. Инженер не тот, кто все знает, а тот кто знает где найти ответ. |
Honey Пользователь Сообщений: 204 |
#3 22.06.2017 08:42:25 Irbis_evs,
Этот в книге:
Воооть… |
||||
The_Prist Пользователь Сообщений: 13997 Профессиональная разработка приложений для MS Office |
Скорее всего проблема в том, что для этого пользователя скрываются все листы до того, как код дойдет до нужного. Создайте еще один лист для служебных нужд. Назовите его «main». В коде Workbook_Open первой строкой отображайте этот лист ВСЕГДА. Далее идет Ваш код. И последней строкой просто скрываете этот служебный лист, проверив, отображен ли помимо него еще хотя бы один лист. Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
Honey Пользователь Сообщений: 204 |
The_Prist, А почему такая проблема возникает только у одного пользователя? Раньше у него был другой компьютер и все работало отлично. А после замены (новый купили) все пошло не так… Этот же пользователь заходит в учетку через мой комп — и все снова работает… Изменено: Honey — 22.06.2017 08:56:28 |
The_Prist Пользователь Сообщений: 13997 Профессиональная разработка приложений для MS Office |
Я выше написал почему такое может быть: для этого ПК(пользователя) Ваш код не оставляет ни одного видимого листа. А это запрещено в книгах, вот и получаете ошибку при попытке скрыть последний видимый лист. Почему происходит именно у Вас — не скажу 100%. Может еще в чем проблема. Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
Vetermsk Пользователь Сообщений: 42 |
#7 22.06.2017 09:04:14
Такое бывает, у меня тоже были примеры, когда код работал неделями на одном компьютере, но выдавал ошибку на другом. |
||
The_Prist Пользователь Сообщений: 13997 Профессиональная разработка приложений для MS Office |
#8 22.06.2017 09:14:05
нет. Попробуйте скрыть лист кодом, а потом попробуйте скрыть его кодом повторно. Ничего не случится. Видимость — это всего лишь свойство листа и если дважды назначить этому свойству одно значение — ничего не измениться и ошибки не вызовет. Озвученная в теме ошибка как правило возникает в двух случаях: Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
||
Vetermsk Пользователь Сообщений: 42 |
#9 22.06.2017 09:18:14
Именно такой случай у меня был. Когда на нескольких компьютерах работало нормально, а на одном вылетала ошибка. И причина была — именно в попытке скрыть скрытый лист. Что-то на том компьютере мешало повторно применить свойство. При всех одинаковых остальных параметрах. Когда поставил проверку, ошибка ушла. Почему так было — понятия не имею, но случай запомнился. Изменено: Vetermsk — 22.06.2017 09:18:38 |
||
Юрий М Модератор Сообщений: 60390 Контакты см. в профиле |
#10 22.06.2017 09:20:16
Не будет — проверьте сами. |
||
Honey Пользователь Сообщений: 204 |
|
Honey Пользователь Сообщений: 204 |
Ой, я только увидела все сообщения))) В общем, с попыткой листа Мэйн мало что вышло. Я не особо дружу с макросами, хоть и приходиться с ними работать. Видимо что-то не так делаю… Сейчас попробую проверить на видимость. |
Honey Пользователь Сообщений: 204 |
Что-то совсем не то… |
Vetermsk Пользователь Сообщений: 42 |
#14 22.06.2017 10:24:08
Это надо вставить вместо 87-й строчки в вашем примере. |
||
Honey Пользователь Сообщений: 204 |
|
Honey Пользователь Сообщений: 204 |
Ошибка не ушла…((( Изменено: Honey — 22.06.2017 11:20:10 |
The_Prist Пользователь Сообщений: 13997 Профессиональная разработка приложений для MS Office |
На какой строке ошибка? У Вас есть две процедуры, где идет скрытие листов. В какой из них появляется эта ошибка? При открытии файла или при закрытии? Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
Honey Пользователь Сообщений: 204 |
The_Prist, Хочу еще добавить: если заходить через этого пользователя на мой ноут (1)-все работает. Через мою учетку на тот ноут (2), где не работало-опять-таки все работает. А через учетку конкретного пользователя на тот самый ноут (2) не работает. Словно это конфликт учетки с ноутом. Знаю звучит странно… Изменено: Honey — 22.06.2017 11:47:13 |
The_Prist Пользователь Сообщений: 13997 Профессиональная разработка приложений для MS Office |
#19 22.06.2017 11:58:16
А Вы снимите сначала пароль с проекта VBA и запустите книгу на проблемном ноутбуке без защиты проекта.
добавьте лист main и измените кусок кода так:
Изменено: The_Prist — 22.06.2017 12:03:08 Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
||||||
Honey Пользователь Сообщений: 204 |
The_Prist, С Вашим кодом у меня только лист main и открыт. А нужно чтобы открывался лист месяца текущего+листы на которые вообще нет когда виден-невиден… Изменено: Honey — 22.06.2017 12:16:54 |
AndreTM Пользователь Сообщений: 454 |
#21 22.06.2017 12:13:16 На самом деле надо:
А то мало ли,чему там True равно |
||
Honey Пользователь Сообщений: 204 |
AndreTM, |
Honey Пользователь Сообщений: 204 |
Уважаемые, Если есть еще идеи, буду очень признательна! |
The_Prist Пользователь Сообщений: 13997 Профессиональная разработка приложений для MS Office |
#24 22.06.2017 12:27:27
Но ошибки нет? Значит вопрос очевиден — ищите различия в названиях учетной записи. Если мой код оставляет открытым только лист main, значит ни одно из условий для отображения других листов не выполняется. Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
||
Honey Пользователь Сообщений: 204 |
The_Prist, |
The_Prist Пользователь Сообщений: 13997 Профессиональная разработка приложений для MS Office |
ну я уже не знаю как объяснить. Копайтесь сами и думайте, что дело в чем-то другом. Убеждать в очевидном уже надоело. Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
Honey Пользователь Сообщений: 204 |
The_Prist, Простите, если я где-то не так объясняю… |
The_Prist Пользователь Сообщений: 13997 Профессиональная разработка приложений для MS Office |
#28 22.06.2017 12:53:36
Но вывод-то какой? Вывод прост — на этом ноуте условия НЕ СОБЛЮДАЮТСЯ. Значит Ваша задача найти ПОЧЕМУ. И сделать это можно элементарно: пройтись через Debug по всему коду Workbook_Open. ВСЕ. Мы тут обсуждаем воздух сейчас. Кроме Вас никто причину не найдет, т.к. нет у нас Вашего ноута проблемного. Вы спрашивали почему ошибка появляется — ответ получен. Изменено: The_Prist — 22.06.2017 12:54:50 Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
||
Honey Пользователь Сообщений: 204 |
#29 22.06.2017 13:43:35 The_Prist, спасибо за все ответы! |
Running a system that is triggered by a control box. The code unprotects nearly all the sheets in the program using the following code (no problems):
Sub UnprotectSheets()
Dim wks As Worksheet
For Each wks In Worksheets
If wks.Name Like "Source Data Table" Or wks.Name Like "Permit Route Dashboard" _
Or wks.Name Like "Administrative Tasks" Or wks.Name Like "RP Calculation" Then GoTo Nextwks
wks.Unprotect Password:="Password"
Nextwks:
Next
End Sub
The program then conducts an analysis. At the end, I want to protect the same sheets, using the following code
Sub ProtectSheets()
Dim wks As Worksheet
For Each wks In Worksheets
If wks.Name Like "Source Data Table" Or wks.Name Like "Permit Route Dashboard" _
Or wks.Name Like "Administrative Tasks" Or wks.Name Like "RP Calculation" Then GoTo Nextwks
wks.Protect Password:="Password"
Nextwks:
Next
End Sub
However — I keep receiving the following error every time:
Run-time error ‘1004’ Method ‘Protect’ of object _Worksheet’ failed
Any help is appreciated. Thank you
asked Jun 21, 2018 at 12:53
2
The problem is that you are trying to protect an already protected sheet. Thus, simply run this:
Option Explicit
Sub TestMe()
Dim wks As Worksheet
For Each wks In Worksheets
If wks.ProtectContents Then
Debug.Print wks.Name & " is protected!"
Else
Debug.Print wks.Name & " is not protected!"
End If
Next wks
End Sub
Then go to the immediate window (Ctrl+G) and take a look at the report written there. It should look like this:
Sheet1 is not protected!
Sheet2 is protected!
In general, try to avoid GoTo
in VBA (and in every programming language), unless it is for error-catching. People become mad when they see these.
answered Jun 21, 2018 at 13:10
VityataVityata
42.1k8 gold badges55 silver badges95 bronze badges
6
Microsoft Excel is one of the most popular spreadsheets used across the globe for both individual and business purposes. It is the one-stop destination for storing, organizing, and manipulating data in an organized way. MS Excel comes mainly in two extensions i.e. XLS and XLSX format. However, apart from its incredible popularity, runtime errors are a common nuisance for many Windows users – and one of the most common ones is the Runtime Error 1004.
In this guide, we are going to discuss this common Runtime error 1004 and some of the best fixes to resolve it effortlessly.
What is Runtime Error 1004 in Excel?
Runtime error 1004 is an error code relating to Microsoft Visual Basic that has been known to disturb Microsoft Excel users. This error is faced by any versions of MS Excel such as Excel 2007, 2010, 2013, 2016, 2019 as well. No version of Microsoft Excel is safe from the menace of Runtime Error 1004. In some cases, you may see the runtime error 1004 in Excel after opening a worksheet. Such types of runtime errors usually occur due to a problematic add-in.
This error is mainly encountered by users while they are working on an excel file or trying to generate a Macro in the excel document. It can cause serious trouble while working with Visual Basic Applications and can completely crash a program, or even the entire system; sometimes it may freeze the system prohibiting the users to do anything on their system.
Types of error message
The error messages that are most associated with this runtime error are as follows:
- VB: run-time error ‘1004’: Application-defined or object-defined error
- Excel VBA Runtime error 1004 “Select method of Range class failed”
- runtime error 1004 method range of object _global failed visual basic
- Excel macro “Run-time error ‘1004?
- Runtime error 1004 method open of object workbooks failed
- Run-Time error ‘1004’: Method ‘Ranger’ of Object’ Worksheet’ Failed
- “Method in Key up Object Program APPLICATION Failed.”
- Run-time error ‘1004’: Activate method of Worksheet class failed
If you encounter any of these above errors, then you can fix the error using our guide.
What are the causes?
The Error 1004 is a general code related to MS Excel but is not specific to one exact cause. Hence, in this case, the exact reason why this error might pop up will vary from case to case and circumstance to circumstance. From configuration issues to software problems, below we listed a synopsis of common reasons for runtime error 1004 in excel:
- MS Excel Desktop Icon might be corrupted
- VBA Excel File is clashing with other application
- Due to application or object specified error
- Due to missing dependent file
- Due to Virus, Trojan or malware
- Due to Invalid Registry Keys and so on.
These were a few of the most common reasons behind getting the runtime error 1004 in MS Excel; now let us understand the different fixes.
Here we have detailed both manual and automatic solutions to fix the Runtime Error 1004. You can follow any one of the next methods to resolve the issue.
- Create a new Excel template
- Launch Excel in Safe Mode
- Run a Virus Scan
- For VB: run-time error ‘1004’, resize legend entries
Let’s look at each of these methods in detail.
1] Create a new Excel template
In some cases, fixing this issue can be as simple as inserting a new worksheet from a template instead of creating a copy of an existing worksheet. Here is what you need to do:
1] Open MS Excel on your system
2] Press ‘CTRL + N’ to create a new Microsoft Excel worksheet or simply select a ‘Blank workbook’ from the first screen.
3] Once done delete all the sheets on the workbook except one.
4] Now, format the workbook, which has been left. Also, note, this workbook can be modified to suit your individual need.
5] In the end, go to ‘File > Save As’ to save the new worksheet with the Excel Template (.xltx or .xlt) file format.
6] Once you have successfully created the template, you can insert it programmatically by using the following line of code:
Sheets.Add Type:=pathfilename
Please note – Do not forget to replace the new filename with the actual name of the document.
2] Launch Excel in Safe Mode
If Excel is showing you the runtime error 1004 after opening an Excel file, there might be a problematic add-in causing the issue. The affected users received the error message given below:
Run-time error ‘1004’: Activate method of Worksheet class failed
To check if the problem is caused by an add-in or not, launch Excel in Safe Mode. If Excel opens successfully in the Safe Mode, the problem was occurring due to an add-in. Now, you have to identify the problematic add-in. To do that, follow the steps provided below:
- In Safe Mode, go to “File > Options > Add-Ins.”
- Select COM Add-ins in the drop-down on the right side and click Go.
- In Safe Mode, some add-ins are disabled. You have to enable the disabled add-ins one by one. Enable one of the disabled add-ins and restart Excel in normal mode. See if the error occurs.
If the error occurs, repeat the above steps again. After you find the problematic add-in, consider removing it from Excel.
3] Run a Virus Scan
It is very important to scan your computer system for malware and viruses as these can corrupt files and important documents and show the runtime error 1004 in MS Excel. Sometimes using a good antivirus program helps a lot.
Related: Run-time error 1004, Cannot run the Macro in Excel.
4] For VB: run-time error ‘1004’, resize legend entries
If you come across a Runtime Error 1004 when running a Microsoft Visual Basic for Applications (VBA) macro, then you can use this method to work-around.
Generally, you get this error when you try to run a VBA macro that uses the LegendEntries method to make changes to legend entries in a Microsoft Excel chart. That time, you may receive the following error message:
Run-time error ‘1004’: Application or object-defined error
This error occurs when the Excel chart contains more legend entries than there is space available to display the legend entries on the Excel chart. When this behavior occurs, Microsoft Excel may truncate the legend entries.
To work around this behavior, create a macro that reduces the font size of the Excel chart legend text before your VBA macro makes changes to the chart legend and then restore the font size of the chart legend so that it is similar to the following macro example.
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
We hope this article helps you fix the runtime error 1004 in Microsoft Excel. This guide gives you manual as well as automatic solution to get rid of this error; you can make use of any solution based on your need.
How do I fix a runtime error?
Runtime errors occur at the time of running a program. The runtime errors usually freeze or crash the affected program or software. To fix a runtime error, you can use general fixes, like installing the latest Microsoft Visual C++ Redistributables, running the SFC and DISM scans, troubleshooting in a Clean Boot state, etc.
Read next: Arrows keys not working in Microsoft Excel.