Runtime error 1004 method saveas of object workbook failed

Hello,        I have code designed to create an archive of my main sheet (as a .xlsx) by copying the sheet > saving the copied sheet in a new workbook > doing things to the sheet within the new workbook > saving and closing new workbook then continuing the rest of my code.         Everything works a...

Hello,

     I have code designed to create an archive of my main sheet (as a .xlsx) by copying the sheet > saving the copied sheet in a new workbook > doing things to the sheet within the new workbook > saving and closing new workbook then continuing the rest of my code. 

     Everything works as coded except when the user selects (or keeps selected) the same file location, in the SaveAs dialog, that the original file (with the running VBA) is in. It returns a «Method ‘SaveAs’ of object ‘_Workbook’ failed» error.

     I created an «If» check to see if the selected file location from the SaveAs dialog is the same as the file location of the original and was able to create an error handler (avoid the error), but not an error solution. I want to default to the same file location as the original, and regardless I want the user to be able to save into the same file location, especially since that is a very typical thing to do.

     Line (59) with error 1004:

ActiveWorkbook.SaveAs fileName:=PathAndFile_Name, FileFormat:=xlOpenXMLWorkbook

     ShiftYear (what code is in) and PleaseWait are userforms, and «Troop to Task — Tracker» is the sheet I’m copying.

Code with error:

'<PREVIOUS CODE THAT DOESN'T PERTAIN TO THE SAVEAS ISSUE>

'''Declare variables:
'General:
Dim NewGenYear As Integer, LastGenYear As Integer, year_create_counter As Integer
NewGenYear = 0: LastGenYear = 0: year_create_counter = 0
'Personnel:
Dim cell_person As Range, cell_num As Range
Dim cell_num_default As Range
'Archive:
Dim Sheet_Archive As Worksheet, ShVal As Integer
Dim ObFD As FileDialog
Dim File_Name As String
Dim PathAndFile_Name As String
Dim Shape_Clr As Shape
Dim cell_color_convert As Range

'<A WHOLE BUNCH OF OTHER CHECKS AND CODE THAT DOESN'T PERTAIN TO THE SAVEAS ISSUE>

'Set then launch SaveAs dialog:
If ShiftYear.CheckBox5.Value = True Then 'Archive <=5 year(s) data externally - Checked:
    For Each Sheet_Archive In ThisWorkbook.Sheets
    Select Case Sheet_Archive.CodeName
    Case Is = "Sheet4", "Sheet5", "Sheet6", "Sheet7"
    ShVal = Sheet_Archive.Name
    If Sheet_Archive.Range("A2").Value <> "N/A" And ShVal <> ShiftYear.Shift_3.Value Then
    File_Name = "Archive " & Sheet_Archive.Name & "_" & ThisWorkbook.Name 'Set default (suggested) File Name
    Set ObFD = Application.FileDialog(msoFileDialogSaveAs)
    With ObFD
        .Title = "Archive Year(s) - Personnel Tracker"
        .ButtonName = "A&rchive"
        .InitialFileName = ThisWorkbook.Path & "" & File_Name 'Default file location and File Name
        .FilterIndex = 1 'File Type (.xlsx)
        .AllowMultiSelect = False
        .InitialView = msoFileDialogViewDetails
        .Show
        If .SelectedItems.count = 0 Then
        MsgBox "Generation and archiving canceled. No year(s) were created, shifted, or overwritten. To continue generating without archiving, uncheck the ""Archive <=5 year(s) calendar/personnel data externally before overwriting"" box then click ""Generate"" again." _
        , vbExclamation, "Year Shift & Creation - Personnel Tracker"
        '<MY CODE THAT TURNS OFF MACRO ENHANCEMENT>
        Exit Sub
        Else
        PathAndFile_Name = .SelectedItems(1)
        End If
    End With
    Application.DisplayAlerts = False
    
'Load year to be archived:
    Worksheets("Formula & Code Data").Range("I7").Value = Sheet_Archive.Name
    Worksheets("Formula & Code Data").Range("I13").Value = "No"
    Call Load_Year.Load_Year

'Copy Troop to Task - Tracker sheet into new workbook and format:
    PleaseWait.Label2.Caption = "Creating " & Sheet_Archive.Name & " archive file ..."
    DoEvents
    File_Name = Right(PathAndFile_Name, Len(PathAndFile_Name) - InStrRev(PathAndFile_Name, "")) 'Update File Name to user's input
    ThisWorkbook.Sheets("Troop to Task - Tracker").Copy

    ActiveWorkbook.SaveAs fileName:=PathAndFile_Name, FileFormat:=xlOpenXMLWorkbook 'New workbook save and activate

    '<ALL MY CODE THAT CHANGES THE NEW WORKBOOK>

    Excel.Workbooks(File_Name).Activate
    Excel.Workbooks(File_Name).Close savechanges:=True 'New workbook save and close
    Application.DisplayAlerts = True
    End If
    End Select
    If (Sheet_Archive.CodeName = "Sheet4" Or Sheet_Archive.CodeName = "Sheet5" _
    Or Sheet_Archive.CodeName = "Sheet6" Or Sheet_Archive.CodeName = "Sheet7") _
    And ShVal <> ShiftYear.Shift_3.Value Then
    PleaseWait.Label2.Caption = "" & Sheet_Archive.Name & " archive file complete"
    DoEvents
    Else: PleaseWait.Label2.Caption = "Initailizing archive ..."
    DoEvents: End If
    Next Sheet_Archive
ElseIf ShiftYear.CheckBox5.Value = False Then 'Archive <=5 year(s) data externally - Unchecked:
    'Do Nothing
End If 'Archive <=5 year(s) data externally - END

'<CONTINUING CODE THAT DOESN'T PERTAIN TO THE SAVEAS ISSUE>

Code with error handler:

'<PREVIOUS CODE THAT DOESN'T PERTAIN TO THE SAVEAS ISSUE>

'''Declare variables:
'General:
Dim NewGenYear As Integer, LastGenYear As Integer, year_create_counter As Integer
NewGenYear = 0: LastGenYear = 0: year_create_counter = 0
'Personnel:
Dim cell_person As Range, cell_num As Range
Dim cell_num_default As Range
'Archive:
Dim Sheet_Archive As Worksheet, ShVal As Integer
Dim ObFD As FileDialog
Dim File_Name As String
Dim PathAndFile_Name As String
Dim Shape_Clr As Shape
Dim cell_color_convert As Range

'<A WHOLE BUNCH OF OTHER CHECKS AND CODE THAT DOESN'T PERTAIN TO THE SAVEAS ISSUE>

'Set then launch SaveAs dialog:
If ShiftYear.CheckBox5.Value = True Then 'Archive <=5 year(s) data externally - Checked:
    For Each Sheet_Archive In ThisWorkbook.Sheets
    Select Case Sheet_Archive.CodeName
    Case Is = "Sheet4", "Sheet5", "Sheet6", "Sheet7"
Archive_Error:
    ShVal = Sheet_Archive.Name
    If Sheet_Archive.Range("A2").Value <> "N/A" And ShVal <> ShiftYear.Shift_3.Value Then
    File_Name = "Archive " & Sheet_Archive.Name & "_" & ThisWorkbook.Name 'Set default (suggested) File Name
    Set ObFD = Application.FileDialog(msoFileDialogSaveAs)
    With ObFD
        .Title = "Archive Year(s) - Personnel Tracker"
        .ButtonName = "A&rchive"
        .InitialFileName = ThisWorkbook.Path & "" & File_Name 'Default file location and File Name
        .FilterIndex = 1 'File Type (.xlsx)
        .AllowMultiSelect = False
        .InitialView = msoFileDialogViewDetails
        .Show
        If .SelectedItems.count = 0 Then
        MsgBox "Generation and archiving canceled. No year(s) were created, shifted, or overwritten. To continue generating without archiving, uncheck the ""Archive <=5 year(s) calendar/personnel data externally before overwriting"" box then click ""Generate"" again." _
        , vbExclamation, "Year Shift & Creation - Personnel Tracker"
        '<MY CODE THAT TURNS OFF MACRO ENHANCEMENT>
        Exit Sub
        Else
        PathAndFile_Name = .SelectedItems(1)
        End If
    End With
    Application.DisplayAlerts = False
    
'Load year to be archived:
    Worksheets("Formula & Code Data").Range("I7").Value = Sheet_Archive.Name
    Worksheets("Formula & Code Data").Range("I13").Value = "No"
    Call Load_Year.Load_Year

'Copy Troop to Task - Tracker sheet into new workbook and format:
    PleaseWait.Label2.Caption = "Creating " & Sheet_Archive.Name & " archive file ..."
    DoEvents
    File_Name = Right(PathAndFile_Name, Len(PathAndFile_Name) - InStrRev(PathAndFile_Name, "")) 'Update File Name to user's input
    ThisWorkbook.Sheets("Troop to Task - Tracker").Copy
    
    If PathAndFile_Name = ThisWorkbook.Path & "" & File_Name Then 'Error handler
Archive_Error_Actual:
    MsgBox "You cannot save into the same location as this Tracker, in this version. Please select a different file location." _
    , vbExclamation, "Year Shift & Creation - Personnel Tracker"
    'UPDATE MESSAGE AND FIGURE OUT WAY TO FIX RUNTIME ERROR WHEN SAVING TO SAME LOCATION AS THE TRACKER!!!
    ActiveWorkbook.Close savechanges:=False
    GoTo Archive_Error
    End If
    On Error GoTo Archive_Error_Actual
    ActiveWorkbook.SaveAs fileName:=PathAndFile_Name, FileFormat:=xlOpenXMLWorkbook 'New workbook save and activate

    '<ALL MY CODE THAT CHANGES THE NEW WORKBOOK>

    Excel.Workbooks(File_Name).Activate
    Excel.Workbooks(File_Name).Close savechanges:=True 'New workbook save and close
    Application.DisplayAlerts = True
    End If
    End Select
    If (Sheet_Archive.CodeName = "Sheet4" Or Sheet_Archive.CodeName = "Sheet5" _
    Or Sheet_Archive.CodeName = "Sheet6" Or Sheet_Archive.CodeName = "Sheet7") _
    And ShVal <> ShiftYear.Shift_3.Value Then
    PleaseWait.Label2.Caption = "" & Sheet_Archive.Name & " archive file complete"
    DoEvents
    Else: PleaseWait.Label2.Caption = "Initailizing archive ..."
    DoEvents: End If
    Next Sheet_Archive
ElseIf ShiftYear.CheckBox5.Value = False Then 'Archive <=5 year(s) data externally - Unchecked:
    'Do Nothing
End If 'Archive <=5 year(s) data externally - END

'<CONTINUING CODE THAT DOESN'T PERTAIN TO THE SAVEAS ISSUE>

Any solution to this is much appreciated!

 

xseed

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

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

#1

05.08.2016 17:50:04

Добрый день! Есть файл xls2txt с макросом, экспортирующий другой файл xls в текст:

Код
Sub Макрос1()
'
' Макрос1 Макрос
    Workbooks.Open Filename:="C:nnCronthebat!1.xls"
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    ActiveWorkbook.SaveAs Filename:="C:nncronthebat!1.txt", FileFormat:= _
        xlUnicodeText, CreateBackup:=False
    ActiveWorkbook.Save
    Application.DisplayAlerts = True
    ActiveWindow.Close False
    Windows("xls2txt.xls").Activate
    Application.Quit
End Sub

при попытке выполнить который выдается это сообщение: Run-time error ‘1004’: Method ‘Saveas’ of object ‘_workbook’ failed

Debug переходит на строку

Код
     ActiveWorkbook.SaveAs Filename:="C:nncronthebat!1.txt", FileFormat:= _
        xlUnicodeText, CreateBackup:=False

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

Прикрепленные файлы

  • 1.zip (18.09 КБ)

Изменено: xseed05.08.2016 18:07:23

 

The_Prist

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

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

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

Тут все просто. Вы пытаетесь сохранить файл, который уже открыт под тем же именем самим Excel. Поэтому VBA и генерирует ошибку — файл занят процессом и не может быть перезаписан. Это недопустимо. Сохраняйте либо в другую папку, либо под другими именем.

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

 

xseed

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

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

#3

05.08.2016 17:59:05

Цитата
The_Prist написал:
Вы пытаетесь сохранить файл, который уже открыт под тем же именем

Я открываю файл xls2txt.xls. Выполняю в нем макрос1. Открывается файл 1.xls, сохраняется как 1.txt. Где тут сохранение под тем же именем? Имя то же. но расширение txt. причем, когда я делал запись макроса, excel спрашивал меня. что файл 1.txt уже существует. заменить? Я согласился, нажав Да.

Изменено: xseed05.08.2016 17:59:30
(ошибка)

 

The_Prist

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

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

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

#4

05.08.2016 18:02:04

Да, проглядел расширение. Сказывается, видимо, пятница :)
Но тем не менее. Файл такой есть и Excel делает запрос на его замену. И незаметно для Вас сначала его удаляет, а потом записывает новый. VBA этого за Вас делать не будет. И ошибка в VBA у Вас явно так же говорит о том, что файл такой уже есть. Поэтому сначала убедитесь, что такого файла нет на диске. Если есть — удаляйте:

Код
If dir("C:nncronthebat!1.txt",16) <> "" then
kill "C:nncronthebat!1.txt" 'удаляем файл, если он есть
end if
ActiveWorkbook.SaveAs Filename:="C:nncronthebat!1.txt", FileFormat:=xlUnicodeText, CreateBackup:=False

P.S. Оформляйте код соответствующим тегом(<…>), а не шрифтом. Так нагляднее будет.

Изменено: The_Prist05.08.2016 18:02:36

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

 

xseed

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

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

The_Prist

, нет, файл 1.txt тут ни причем. Если вы выполните мой макрос с обычным xls файлом, никаких ошибок не возникнет, файл сохранится как txt, даже если он существует. Проблема возникнет, только если выполнить макрос с прикрепленным файлом 1.xls (причем его надо поместить в каталог C:nnCronthebat!)

PS: прикрепил файл с макросом xls2txt.xls

Изменено: xseed05.08.2016 18:12:04

 

The_Prist

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

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

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

Пароль к проекту какой? Может там еще какое событие срабатывает.

Изменено: The_Prist05.08.2016 18:17:59

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

 

xseed

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

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

Это не мой файл, пароля не знаю.
Может быть, потому, что в 1.xls установлен VBAProject Password, макрос в файле xls2txt не отрабатывает?
Тогда экспорт вручную в txt на этом файле 1.xls почему тогда работает?

Изменено: xseed05.08.2016 18:29:52

 

xseed

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

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

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

Изменено: xseed05.08.2016 18:33:47

 

The_Prist

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

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

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

#9

05.08.2016 18:32:39

Тогда сделайте так:

Код
Sub Макрос1()
'
' Макрос1 Макрос
'

'
    Workbooks.Open Filename:="C:nnCronthebat!1.xls"
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    ActiveWorkbook.Sheets(1).Copy
    ActiveWorkbook.SaveAs Filename:="C:nncronthebat!1.txt", FileFormat:= _
        xlUnicodeText, CreateBackup:=False
    ActiveWorkbook.Save
    Application.DisplayAlerts = True
    ActiveWindow.Close False
    Windows("xls2txt.xls").Activate
    Application.Quit
End Sub

больше одного листа все равно не сохраните в txt

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

 

xseed

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

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

#10

05.08.2016 18:40:31

Цитата
The_Prist написал:
ActiveWorkbook.Sheets(1).Copy

Спасибо!
А как работает эта команда? Просто копирует лист или же копирует книгу? Тогда в чем причина проблемы?

Изменено: xseed05.08.2016 18:40:53

 

The_Prist

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

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

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

#11

05.08.2016 18:44:31

Эта команда копирует один(в данном случае первый) лист в новую книгу. Книга создается автоматически.
В чем проблема? В том, что есть пароль на проект. А файл Вы кодом сохраняете без этого самого проекта. И т.к. там есть пароль на проект VBA — то доступа к проекту извне нет для его модификации. А удаление — та еще модификация. Т.е. по факту Вы не можете сохранить данный файл в любом формате, который не поддерживает хранение VBA проекта. А при копировании листа создается новая книга с одним лишь листом и без всяких проектов и защиты.

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

Содержание

  1. Error message when you run a Visual Basic for Applications macro in Excel: «Method ‘SaveAs’ of object ‘_Worksheet’ failed»
  2. Symptoms
  3. Cause
  4. Workaround
  5. Status
  6. Error message when you run a Visual Basic for Applications macro in Excel: «Method ‘SaveAs’ of object ‘_Worksheet’ failed»
  7. Symptoms
  8. Cause
  9. Workaround
  10. Status
  11. Error message when you run a Visual Basic for Applications macro in Excel: «Method ‘SaveAs’ of object ‘_Worksheet’ failed»
  12. Symptoms
  13. Cause
  14. Workaround
  15. Status
  16. Как исправить ошибку выполнения 1004 в Microsoft Excel?
  17. Что такое ошибка времени выполнения 1004 в Excel?
  18. Типы сообщений об ошибках
  19. Каковы причины?
  20. Исправить ошибку выполнения 1004 в Excel
  21. 1]Создайте новый шаблон Excel
  22. 2]Запустите сканирование на вирусы
  23. 3]Для VB: ошибка времени выполнения «1004», измените размер записей легенды.

Error message when you run a Visual Basic for Applications macro in Excel: «Method ‘SaveAs’ of object ‘_Worksheet’ failed»

Symptoms

When you run a Visual Basic for Applications macro in Microsoft Excel, you may receive the following or similar error message:

Run-time error ‘1004’:
Method ‘SaveAs’ of object ‘_Worksheet’ failed

Cause

This behavior can occur when both the following conditions are true:

You are using a Visual Basic for Applications macro to save a worksheet.

You specify the file format as the constant xlWorkbookNormal.

For example, the following code causes this error to occur:

Workaround

Microsoft provides programming examples for illustration only, without warranty either expressed or implied, including, but not limited to, the implied warranties of merchantability and/or fitness for a particular purpose. This article assumes that you are familiar with the programming language being demonstrated and the tools used to create and debug procedures. Microsoft support professionals can help explain the functionality of a particular procedure, but they will not modify these examples to provide added functionality or construct procedures to meet your specific needs.
If you have limited programming experience, you may want to contact a Microsoft Certified Partner or Microsoft Advisory Services. For more information, visit these Microsoft Web sites:

For more information about the support options that are available and about how to contact Microsoft, visit the following Microsoft Web site:http://support.microsoft.com/default.aspx?scid=fh;EN-US;CNTACTMS

To work around this behavior, change the file format specification from the constant xlWorkbookNormal to 1. The example code functions normally if changed to:

NOTE Even though you are saving a worksheet, all worksheets in the selected workbook are saved when the file format is set to xlWorkbookNormal or 1.

Status

Microsoft has confirmed that this is a problem in the Microsoft products that are listed at the beginning of this article.

Источник

Error message when you run a Visual Basic for Applications macro in Excel: «Method ‘SaveAs’ of object ‘_Worksheet’ failed»

Symptoms

When you run a Visual Basic for Applications macro in Microsoft Excel, you may receive the following or similar error message:

Run-time error ‘1004’:
Method ‘SaveAs’ of object ‘_Worksheet’ failed

Cause

This behavior can occur when both the following conditions are true:

You are using a Visual Basic for Applications macro to save a worksheet.

You specify the file format as the constant xlWorkbookNormal.

For example, the following code causes this error to occur:

Workaround

Microsoft provides programming examples for illustration only, without warranty either expressed or implied, including, but not limited to, the implied warranties of merchantability and/or fitness for a particular purpose. This article assumes that you are familiar with the programming language being demonstrated and the tools used to create and debug procedures. Microsoft support professionals can help explain the functionality of a particular procedure, but they will not modify these examples to provide added functionality or construct procedures to meet your specific needs.
If you have limited programming experience, you may want to contact a Microsoft Certified Partner or Microsoft Advisory Services. For more information, visit these Microsoft Web sites:

For more information about the support options that are available and about how to contact Microsoft, visit the following Microsoft Web site:http://support.microsoft.com/default.aspx?scid=fh;EN-US;CNTACTMS

To work around this behavior, change the file format specification from the constant xlWorkbookNormal to 1. The example code functions normally if changed to:

NOTE Even though you are saving a worksheet, all worksheets in the selected workbook are saved when the file format is set to xlWorkbookNormal or 1.

Status

Microsoft has confirmed that this is a problem in the Microsoft products that are listed at the beginning of this article.

Источник

Error message when you run a Visual Basic for Applications macro in Excel: «Method ‘SaveAs’ of object ‘_Worksheet’ failed»

Symptoms

When you run a Visual Basic for Applications macro in Microsoft Excel, you may receive the following or similar error message:

Run-time error ‘1004’:
Method ‘SaveAs’ of object ‘_Worksheet’ failed

Cause

This behavior can occur when both the following conditions are true:

You are using a Visual Basic for Applications macro to save a worksheet.

You specify the file format as the constant xlWorkbookNormal.

For example, the following code causes this error to occur:

Workaround

Microsoft provides programming examples for illustration only, without warranty either expressed or implied, including, but not limited to, the implied warranties of merchantability and/or fitness for a particular purpose. This article assumes that you are familiar with the programming language being demonstrated and the tools used to create and debug procedures. Microsoft support professionals can help explain the functionality of a particular procedure, but they will not modify these examples to provide added functionality or construct procedures to meet your specific needs.
If you have limited programming experience, you may want to contact a Microsoft Certified Partner or Microsoft Advisory Services. For more information, visit these Microsoft Web sites:

For more information about the support options that are available and about how to contact Microsoft, visit the following Microsoft Web site:http://support.microsoft.com/default.aspx?scid=fh;EN-US;CNTACTMS

To work around this behavior, change the file format specification from the constant xlWorkbookNormal to 1. The example code functions normally if changed to:

NOTE Even though you are saving a worksheet, all worksheets in the selected workbook are saved when the file format is set to xlWorkbookNormal or 1.

Status

Microsoft has confirmed that this is a problem in the Microsoft products that are listed at the beginning of this article.

Источник

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

Майкрософт Эксель — одна из самых популярных электронных таблиц, используемых во всем мире как для личных, так и для деловых целей. Это универсальное место для хранения, организации и обработки данных организованным способом. 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

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

  1. Создать новый шаблон Excel
  2. Запустите сканирование на вирусы
  3. Для 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 внесет изменения в легенду диаграммы, а затем восстановите размер шрифта легенды диаграммы, чтобы он был похож на следующий пример макроса. .

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

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

Источник

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  1. 09-12-2014, 11:11 AM


    #1

    Angsome is offline


    Registered User


    Runtime Error ‘1004’ Method ‘SaveAs’ of object’_Workbook Failed

    Hi Everyone
    This Forum has been a life saver on numerous occasions.
    The code that follows has been courtesy of this forum and the extensive help i received from everyone.

    But after an year of using the following code it is giving me the following error:

    Runtime Error ‘1004’ Method ‘SaveAs’ of object’_Workbook Failed

    It worked for a while ( 1 year) and then suddenly failed.

    A little background on the code.

    The code basically is suppose to compare the system date (date on your computer) to a date on the excel file. If the system year is larger than date on the excel file then the system will complete a sort function and then save the file in the following locations

    myPath = «S:AdminDocsFinancePurchasingCommonNon-Conforming POs-DatabaseArchive» in other words does a backup.

    The system does the same for month and for date. So if system year is same as excel file year then we compare the month, and if month on the system is higher then the system does a sort and a backup.

    That’s where the SaveAs runtime error comes in. As far as I know that’s where it is failing. I am a bit confused what is causing this problem.

    I would really appreciate help, I am so frustrated.

    Thanks

    Last edited by Angsome; 09-12-2014 at 12:30 PM.


  2. 09-12-2014, 11:50 AM


    #2

    Re: Runtime Error ‘1004’ Method ‘SaveAs’ of object’_Workbook Failed

    I think you need to change

    FileFormat:=1

    to

    FileFormat:=51

    Bernie Deitrick
    Excel MVP 2000-2010


  3. 09-12-2014, 12:57 PM


    #3

    Angsome is offline


    Registered User


    Re: Runtime Error ‘1004’ Method ‘SaveAs’ of object’_Workbook Failed

    Hi Bernie
    Thanks for the reply

    I have tried them all. Here is a list of alternatives I have tried thus far. Starting with the most recent. So 51 was my original number.

    ‘.SaveAs myPath

    ‘.SaveAs myPath, FileFormat:=0

    ‘.SaveAs «S:AdminDocsFinancePurchasingCommonNon-Conforming POs-DatabaseArchive1sName.xlsx»

    ‘ .SaveAs myPath _
    & «» & sName & «.xlsx», _
    FileFormat:=1

    ‘.SaveAs myPath _
    & «» & sName & «.xlsx», _
    FileFormat:=51

    Hope this helps and I hope you can help out


  4. 09-12-2014, 01:30 PM


    #4

    Re: Runtime Error ‘1004’ Method ‘SaveAs’ of object’_Workbook Failed

    Where is your macro located? Are you trying to save Thisworkbook?


  5. 09-12-2014, 02:36 PM


    #5

    Angsome is offline


    Registered User


    Re: Runtime Error ‘1004’ Method ‘SaveAs’ of object’_Workbook Failed

    my location of folder location was wrong. Thanks for the advice everyone.


  6. 09-12-2014, 02:39 PM


    #6

    Angsome is offline


    Registered User


    Re: Runtime Error ‘1004’ Method ‘SaveAs’ of object’_Workbook Failed

    how do i mark it as solved gentleman?


  7. 09-12-2014, 02:58 PM


    #7

    Re: Runtime Error ‘1004’ Method ‘SaveAs’ of object’_Workbook Failed

    Click Thread Tools above your first post, select «Mark your thread as Solved». Or click the Edit button on your first post in the thread, Click Go Advanced, select [SOLVED] from the Prefix dropdown, then click Save Changes.


  • #1

Hi,

I have the following code that I have been using for a few days with no problem, and today I started getting ‘Run time 1004’ error messages.

I am creating a new workbook, combining the contents of cell B1 and Y2 to create a file name and saving it as a .xlsm file.

Code:

Code:

Sub NewWB()
Dim name1 As String
Dim name2 As String

name1 = ActiveWorkbook.Sheets(1).Range("B1").Value
name2 = ActiveWorkbook.Sheets(1).Range("Y2").Value

Application.ScreenUpdating = False
Workbooks.Add
'Saving the Workbook
ActiveWorkbook.SaveAs "C:DRCp and Cpk" & name1 & " " & name2 & ".xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False

Workbooks("SPC V1.xlsm").Sheets("Job dimensions").Activate
Call data
ActiveWorkbook.Save
ActiveWindow.Close
End Sub

Any help with this would be greatly appreciated.

Regards

DR

Last used cell?

Press Ctrl+End to move to what Excel thinks is the last used cell.

  • #2

Not sure this is the issue as you have used it before but I wouldn’t have thought you need the » before name1

ActiveWorkbook.SaveAs «C:DRCp and Cpk» name1 & » » & name2 & «.xlsm», FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False

  • #3

Hi

One of the reasons would be an invalid name

Before the saving check the value of the name:

Code:

MsgBox "C:DRCp and Cpk" & name1 & " " & name2 & ".xlsm"

What do you get (when the saving fires the error)?

  • #4

Hi, by adding in this line, I get a msgbox saying C:DRCp and Cpk .xlsm, which appears to be the problem, vba is not pulling data from B1 and Y2 to create the file name. But nothing has changed since it was working. Are name1 and name2 defined correctly (dim as string)?

  • #5

I have removed the activesheet line where name1 and name2 were defined and added in the specific location, i.e. Workbook, sheet and cell range and now it appears to be working.

Code:

name1 = Workbooks("SPC V1.xlsm").Sheets("Job dimensions").Range("B1").Value
name2 = Workbooks("SPC V1.xlsm").Sheets("Job dimensions").Range("Y2").Value

instead of:

Code:

name1 = ActiveWorkbook.Sheets(1).Range("B1").Value name2 = ActiveWorkbook.Sheets(1).Range("Y2").Value

  • #6

I’m glad you figured it out and it’s working now.

Joe4

  1. 03-03-2017, 07:52 AM


    #1

    Run-time error ‘1004’: Method ‘SaveAs’ of object’_Workbook’ failed

    Hello

    I am trying to create a macro to take data from a worksheet and create and save separate workbooks based upon unique values in a specific column. I found some code which I managed to modify, (with help), and it gets to the point of creating the first workbook but it hangs on the SaveAs. I have tried researching file formats, etc., and changing the location where it saves but I am still getting this «

    Run-time error ‘1004’: Method ‘SaveAs’ of object’_Workbook’ failed» error at this line: wb.SaveAs ThisWorkbook.Path & «C:Usersburls5DesktopCreated Files» & c.Value & «.xlsx»

    Advice appreciated.

    Sub splitCUbycolumn()
    Dim wb As Workbook, sh As Worksheet, ssh As Worksheet, lr As Long, rng As Range, c As Range, lc As Long
    Set sh = Sheets(1)
    lr = sh.Cells(Rows.Count, "M").End(xlUp).Row
    lc = sh.Cells.Find("*", , xlFormulas, xlPart, xlByColumns, xlPrevious).Column
    sh.Range("A" & lr + 2).CurrentRegion.Clear
    sh.Range("M1:M" & lr).AdvancedFilter xlFilterCopy, , sh.Range("A" & lr + 2), True
    Set rng = sh.Range("A" & lr + 3, sh.Cells(Rows.Count, 1).End(xlUp))
        For Each c In rng
            Set wb = Workbooks.Add
            Set ssh = wb.Sheets(1)
            ssh.Name = c.Value
            sh.Range("A1", sh.Cells(lr, lc)).AutoFilter 12, c.Value
            sh.Range("A1", sh.Cells(lr, lc)).SpecialCells(xlCellTypeVisible).Copy ssh.Range("A1")
            sh.AutoFilterMode = False
        wb.SaveAs ThisWorkbook.Path & "C:Usersburls5DesktopCreated Files" & c.Value & ".xlsx"
        wb.Close False
        Set wb = Nothing
        Next
    sh.Range("A" & lr + 2, sh.Cells(Rows.Count, 1).End(xlUp)).Delete
    End Sub


  2. 03-03-2017, 08:09 AM


    #2

    This puts the Path in twice

    wb.SaveAs ThisWorkbook.Path & "C:Usersburls5DesktopCreated Files" & c.Value & ".xlsx"

    Try something like this

    MsgBox ThisWorkbook.Path & "Created Files" & c.Value & ".xlsx" (Delete when correct)
    
    wb.SaveAs ThisWorkbook.Path & "Created Files" & c.Value & ".xlsx"

    ———————————————————————————————————————

    Paul

    Remember: Tell us WHAT you want to do, not HOW you think you want to do it

    1. Use [CODE] ….[/CODE ] Tags for readability
    [CODE]PasteYourCodeHere[/CODE ] — (or paste your code, select it, click [#] button)
    2. Upload an example
    Go Advanced / Attachments — Manage Attachments / Add Files / Select Files / Select the file(s) / Upload Files / Done
    3. Mark the thread as [Solved] when you have an answer
    Thread Tools (on the top right corner, above the first message)
    4. Read the Forum FAQ, especially the part about cross-posting in other forums
    http://www.vbaexpress.com/forum/faq…._new_faq_item3


  3. 03-03-2017, 08:30 AM


    #3

    Thank-you, that worked perfectly!


 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.

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…

Понравилась статья? Поделить с друзьями:
  • Runtime error 1004 method range of object worksheet failed
  • Runtime error 1004 method range of object global failed
  • Runtime error 1004 excel vba как исправить
  • Runtime error 1004 excel application defined or object defined error
  • Runtime error 1004 application defined or object defined error vba