Pivot table runtime error 1004

Hi guys, I am writing a macro to go through a workbook and update the data connection for each pivot table. This is to facilitate refreshing a distributed workbook that contains many pivot tables. This code works perfectly for most occasions, but while refreshing a workbook with 25+ PivotTables, sometimes it errors out with no apparent cause... Usually towards the end of the process.  Note: Code is truncated a bit For i = 1 To Sheets.Count         For Each targetPT In ActiveWorkbook.Sheets(i).PivotTables tryConnection:                     On Error GoTo changeConnectionError                                          targetPT.ChangeConnection ActiveWorkbook.Connections(Command.Offset(0, 2).Value2)                                          Status.append ("Connected")                                          GoTo changeConnectionOk:                      changeConnectionError:                     Status.append ("Failed")         Next targetPT Next i Debugging shows that the PivotTable has a valid connection (the old one I wish to replace) Command.Offset(0,2).Value2 is valid and the ActiveWorkbook.Connection is also valid. I have tried to continue by forcing the loop to the next pivotTable, but any further calls to PivotTable.ChangeConnection or PivotTable.Refresh fail with the 1004 error. Could this be caused by Excel, the macro or a broken PivotTable? Furthermore, how can I work around this to inform the user instead of Excel displaying a generic run-time error? Thanks and regards, Laszlo
  • Remove From My Forums
  • Question

  • Hi guys,

    I am writing a macro to go through a workbook and update the data connection for each pivot table. This is to facilitate refreshing a distributed workbook that contains many pivot tables.

    This code works perfectly for most occasions, but while refreshing a workbook with 25+ PivotTables, sometimes it errors out with no apparent cause… Usually towards the end of the process. 

    Note: Code is truncated a bit

    For i = 1 To Sheets.Count
            For Each targetPT In ActiveWorkbook.Sheets(i).PivotTables
    
    tryConnection:
                        On Error GoTo changeConnectionError
                        
                        targetPT.ChangeConnection ActiveWorkbook.Connections(Command.Offset(0, 2).Value2)
                        
                        Status.append ("Connected")
                        
                        GoTo changeConnectionOk:
                        
    changeConnectionError:
    
                        Status.append ("Failed")
    
            Next targetPT
    Next i
    

    Debugging shows that the PivotTable has a valid connection (the old one I wish to replace) Command.Offset(0,2).Value2 is valid and the ActiveWorkbook.Connection is also valid. I have tried to continue by forcing the loop to the next pivotTable,
    but any further calls to PivotTable.ChangeConnection or PivotTable.Refresh fail with the 1004 error.

    Could this be caused by Excel, the macro or a broken PivotTable?

    Furthermore, how can I work around this to inform the user instead of Excel displaying a generic run-time error?

    Thanks and regards, Laszlo

Answers

  • You already have an error handler in place. Maybe the 1004 is not interceptable. You could try to set Application.DisplayAlerts = False and check the err object after the ChangeConnection command:

    On Error Resume Next
    Application.DisplayAlerts = False
    
    For i = 1 To Sheets.Count
        For Each targetPT In ActiveWorkbook.Sheets(i).PivotTables
              Err.Clear
              targetPT.ChangeConnection ActiveWorkbook.Connections(Command.Offset(0, 2).Value2)
              If Err = 0 Then
                Status.append ("Connected")
              Else
                Status.append ("Failed - " & Err.Description)
                MsgBox Err.Description, , Err.Number
              End If
        Next targetPT
    Next i
    Application.DisplayAlerts = True
    
    • Proposed as answer by

      Friday, July 22, 2011 8:58 AM

    • Marked as answer by
      Max Meng
      Monday, July 25, 2011 7:10 AM

  • #2

The error message means that one or more of these pivot tables are not present in Data sheet.

  • #3

I decided to start over and make it as simple as possible. I created a whole new workbook and created 1 pivot table off of the data source. I still got the error. I tried putting the code in this workbook instead of the data sheet and now I can make changes to the data source without getting a error. But when I looked at the pivot table its not updating automatically. Below is the code I am using. My data sheet is Sheet1 and my pivot table is Sheet2. I am so confused.

Private Sub Worksheet_Change(ByVal Target As Range)
Worksheets(«Sheet1»).PivotTables(«Sheet2»).PivotCache.Refresh
End Sub

I have one data source sheet and 3 pivot tables that I want to all update automatically. I am getting this run-time error 1004 when I try to input a new row or make any changes. Below is the code I have for all 3 pivot tables. Can someone help me please?

Run-time error 1004 Unable to get the PivotTables properties of the worksheet class.

Private Sub Worksheet_Change(ByVal Target As Range)
Worksheets(«Data»).PivotTables(«PivotTable1»).PivotCache.Refresh
Worksheets(«Data»).PivotTables(«PivotTable2»).PivotCache.Refresh
Worksheets(«Data»).PivotTables(«PivotTable3»).PivotCache.Refresh
End Sub

  • #4

Worksheet_Change is the name for sheet’s event procedure — if you wanted the code to run every time you update Sheet2, then place Worksheet_Change code in VBA module of Sheet2.

At workbook level, the name of procedure is Workbook_SheetChange — it runs if any of the sheet is changed.

Also disable events before refreshing pivot cache.

Worksheet module code (whichever sheet’s update should trigger refresh):

Code:

Private Sub Worksheet_Change(ByVal Target As Range)
    Application.EnableEvents = False
    Worksheets("Sheet1").PivotTables("Sheet2").PivotCache.Refresh
    Application.EnableEvents = True

End Sub

Workbook module code (if updating any of the sheets should trigger a refresh):

Code:

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
    Application.EnableEvents = False
    Worksheets("Sheet1").PivotTables("Sheet2").PivotCache.Refresh
    Application.EnableEvents = True
End Sub

  • #5

Thank you for this by the way. What would be the code if I had multiple pivot tables to automatically update from one source data sheet?

Worksheet_Change is the name for sheet’s event procedure — if you wanted the code to run every time you update Sheet2, then place Worksheet_Change code in VBA module of Sheet2.

At workbook level, the name of procedure is Workbook_SheetChange — it runs if any of the sheet is changed.

Also disable events before refreshing pivot cache.

Worksheet module code (whichever sheet’s update should trigger refresh):

Code:

Private Sub Worksheet_Change(ByVal Target As Range)
    Application.EnableEvents = False
    Worksheets("Sheet1").PivotTables("Sheet2").PivotCache.Refresh
    Application.EnableEvents = True

End Sub

Workbook module code (if updating any of the sheets should trigger a refresh):

Code:

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
    Application.EnableEvents = False
    Worksheets("Sheet1").PivotTables("Sheet2").PivotCache.Refresh
    Application.EnableEvents = True
End Sub

  • #6

If both pivot table refresh depend on same sheet: If you have two pivot tables (Pivot1 in Sheet1 and Pivot2 in Sheet2) in that need to be refreshed whenever a change in Sheet5 occurs, your Sheet5 module code will be:

Code:

Private Sub Worksheet_Change(ByVal Target As Range)
    Application.EnableEvents = False
    Worksheets("Sheet1").PivotTables("Pivot1").PivotCache.Refresh
    Worksheets("Sheet2").PivotTables("Pivot2").PivotCache.Refresh
    Application.EnableEvents = True
End Sub

If each pivot table depends on a different sheet: Create Worksheet_Change for each sheet in which data is being changed to trigger Refresh. Or use the Workbook module event code Workbook_SheetChange().

  1. Jul 30th, 2017, 09:07 PM


    #1

    Koolmint1090 is offline

    Thread Starter


    Registered User


    Resolved [RESOLVED] Code to create pivot table — runtime error 1004

    Hello VB Gurus,

    Below is my code to build a pivot table with a dynamic range. I’m getting a runtime error 1004 — unable to get the pivot table property of the workclass sheet. The error comes up at line With ActiveSheet.PivotTables(«PTable»).PivotFields(«Work Centre»)

    Sub Create_Pivot()

    Dim PSheet As Worksheet
    Dim DSheet As Worksheet
    Dim PCache As PivotCache
    Dim PTable As PivotTable
    Dim PRange As Range
    Dim LastRow As Long
    Dim LastCol As Long

    ‘Set Pivot Table & Source Worksheet
    Set DSheet = Worksheets(«Sheet1»)
    Set PSheet = Worksheets(«Pivot»)

    ‘Defining Staring Point & Dynamic Range
    DSheet.Activate
    LastRow = DSheet.Cells(Rows.Count, 1).End(xlUp).Row
    LastCol = DSheet.Cells(1, Columns.Count).End(xlToLeft).Column
    Set PRange = DSheet.Cells(1, 1).Resize(LastRow, LastCol)

    Set PCache = ActiveWorkbook.PivotCaches.Create(xlDatabase, DSheet.Range(«A1»).CurrentRegion)

    Set PTable = PCache.CreatePivotTable(TableDestination:=PSheet.Cells(1, 1))

    With ActiveSheet.PivotTables(«PTable»).PivotFields(«Work Centre»)
    .Orientation = xlRowField
    .Position = 1
    End With
    With ActiveSheet.PivotTables(«PTable»).PivotFields(«Status»)
    .Orientation = xlRowField
    .Position = 2
    End With
    With ActiveSheet.PivotTables(«PTable»).PivotFields(«Safety»)
    .Orientation = xlColumnField
    .Position = 1
    End With
    ActiveSheet.PivotTables(«PTable»).AddDataField ActiveSheet.PivotTables( _
    «PTable»).PivotFields(«System status»), «Count of System status», xlCount
    End Sub

    Thanks in advance for your help


  2. Jul 31st, 2017, 03:59 AM


    #2

    Re: Code to create pivot table — runtime error 1004

    why would you be using the activesheet object when you already have a sheet object for your pivot table sheet?

    as far as i can tell the activesheet, at that point, is not the one with the pivot tables, but dsheet, hence the error

    what is prange for? it is assigned a value, but not used within the code posted

    pls use code tags when posting code

    i do my best to test code works before i post it, but sometimes am unable to do so for some reason, and usually say so if this is the case.
    Note code snippets posted are just that and do not include error handling that is required in real world applications, but avoid On Error Resume Next

    dim all variables as required as often i have done so elsewhere in my code but only posted the relevant part

    come back and mark your original post as resolved if your problem is fixed
    pete


  3. Aug 2nd, 2017, 08:29 PM


    #3

    Koolmint1090 is offline

    Thread Starter


    Registered User


    Re: Code to create pivot table — runtime error 1004

    Thanks Westconn1 for replying to my post.

    The code was taken from blog site and when the blog’s author didn’t replay to my question, I posted it here. Following on from your feedback I’ve re-recorded the macro and made the changes I needed to give the dynamic range. The macro now works.

    Thanks again for your help.


I have created a VBA macro to create several pivot tables from a report exported from JDE. The macro works fine, but before I can run the macro, I have to use the Convert Text to Table function on the exported data, then save the file. I wish to automate this process, and have added the code below before the code which creates the pivot tables.

My problem is that when I run this macro, it always results in a Run-time error. The error message is:

Run-time error ‘1004’:
Unable to get the PivotFields property of the PivotTable class

Could you please tell me what is causing this error, and how do I solve it.

————————————————— ————————-
Code to prepare data before creating the PivotTable
————————————————— ————————-

Selection.TextToColumns Destination:=Range(«»A1″»), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:lse, Tab:lse, _
Semicolon:lse, Comma:=True, Space:lse, Other:lse, FieldInfo _
:=Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1), Array(6, 1), _
Array(7, 1), Array(8, 1), Array(9, 1), Array(10, 1), Array(11, 1), Array(12, 1), Array(13, 1 _
), Array(14, 1), Array(15, 1)), TrailingMinusNumbers:=True
Columns(«»M:M»»).EntireColumn.AutoFit
Range(«»A2″»).Select
Sheets(ActiveSheet.Name).Select
Sheets(ActiveSheet.Name).Name = «»RAW»»
ActiveWorkbook.SaveAs («»T:DeonExcelCevaReportsMonthly2010TI & C PhaseResults Checking Pivot Table.xls»»)
ActiveWorkbook.Close
Workbooks.Open Filename:=»»T:DeonExcelCevaReportsMonthly2010T I & C PhaseResults Checking Pivot Table.xls»»

——————————————-
Code to create the PivotTable
——————————————-

Dim rnn As String
rnn = «»pvtsource»»

Sheets.Add
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDat abase, SourceData:= _
rnn, Version:=xlPivotTableVersion10).CreatePivotTable _
TableDestination:=»»Sheet1!R3C1″», TableName:=»»PivotTable1″», DefaultVersion _
:=xlPivotTableVersion10
Sheets(«»Sheet1″»).Select
Cells(3, 1).Select
With ActiveSheet.PivotTables(«»PivotTable1″»).PivotFields( «»Cost Object 1″»)
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables(«»PivotTable1″»).PivotFields( «»Cost Object 3″»)
.Orientation = xlColumnField
.Position = 1
End With
ActiveSheet.PivotTables(«»PivotTable1″»).CalculatedFi elds.Add «»Balance»», _
«»=Cr?dit -D?bit»», True
ActiveSheet.PivotTables(«»PivotTable1″»).PivotFields( «»Balance»»).Orientation = _
xlDataField
With ActiveSheet.PivotTables(«»PivotTable1″»).PivotFields( «»Sum of Balance»»)
.NumberFormat = «»#,##0.00_);[Red](#,##0.00)»»
End With
Sheets(«»Sheet1″»).Select
Sheets(«»Sheet1″»).Name = «»PIVOT-IS»»

Read these next…

  • Curated Can't communicate with scanner

    Can’t communicate with scanner

    Hardware

    Hello everyone,I have a client that uses Kodak ScanMate i940 scanners at their desks. They recently got a new computer that we prepped and put on their domain. This new computer is recognizing the scanner but it is unusable with the error «can’t communica…

  • Curated Different MAC address, same computer name - multiple DHCP leases

    Different MAC address, same computer name — multiple DHCP leases

    Windows

    I’m noticing a lot more now that our Wifi DHCP scopes are filled by the same computer name, but with different mac addresses. I know there’s a feature in Windows 10 called Random hardware addresses, but that setting is off. Is there anything else that cou…

  • Curated Snap! -- No-Password Logins, Solar Powered Water Filter, Glitch in the Matrix?

    Snap! — No-Password Logins, Solar Powered Water Filter, Glitch in the Matrix?

    Spiceworks Originals

    Your daily dose of tech news, in brief.

    Welcome to the Snap!

    Flashback: February 9, 1996: Introduction of the Bandai Pippin (Read more HERE.)

    Bonus Flashback: February 9, 1990: Galileo Probe does a Venus Flyby (Read more HERE.)

    You nee…

  • Curated Roku TV being used as Wallboard Issues

    Roku TV being used as Wallboard Issues

    Hardware

    Helping someone out at their shop. They have 4 large Roku screens and 2 laptops with dual HDMI ports for video. They are viewing static website business dashboards and PowerPoint. At first all 4 screens connected to wireless, worked for a while but with a…

  • Curated Charging for SSO

    Charging for SSO

    Security

    We have SSO set up with around 5 or 6 solution providers via our M365. Not one of them charges for this, they just sent us the documentation.I identified another online service in use by one of our departments which would benefit from using SSO for staff …

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

Four ways to fix runtime error 1004 in Excel:

Workable Solutions Step-by-step Troubleshooting
Fix 1. Delete the GWXL97.XLA Files Fix the Excel error 1004 is to find and delete the error file. Go to C:Program FilesMS OfficeOfficeXLSTART…Full steps
Fix 2. Check the Trust Access to the VBA Project Object Model Enable a VBA project trust option in Excel Trust Center to fix Excel error 1004. Open a blank Excel file…Full steps
Fix 3. Create Another Excel Template Start a new Excel workbook and make sure there is only one worksheet in it. Format the workbook first…Full steps
Fix 4. Repair Corrupted Excel File Repair corrupted Excel files with a file recovery tool. EaseUS file repair tool fixes severely corrupted XLS and XLSX files and retrieves everything from Excel…Full steps

Microsoft Visual Basic for Applications (VBA) is developed to help users write programs for the Windows operating system. It runs as an internal programming language in Microsoft Office, such as Word, Excel, and PowerPoint.

Some users have reported that when running VBA in an Excel chart or trying to generate a Macro in Excel documents, an error message popped up saying: Runtime error 1004. And then they find themselves cannot access the Excel files. If you have the same encounter as these users, this post is the right place for you. You can find both the reasons and the corresponding solutions of this error code on this page.

How to Fix Excel Error 104

Runtime Error Details

The error message contains more information than the error code 1004. Generally, follow the error code, you can see a brief description. The most repeated error messages are listed below:

  1. Runtime error 1004: Application or object-defined error.
  2. Runtime error 1004: Method Ranger of Object Worksheet failed.
  3. Runtime error 1004: Copy Method of Worksheet Class failed.

The Reason Why You See Runtime Error 1004 in Excel

If you want to know how to fix runtime error 1004 in Excel properly, you need to understand what leads to this issue. The following are the most prominent reasons.

  • Macro Name Error

The Macro you are running is copying the original worksheet to a workbook with a defined name that you did not save and close before running the Macro.

  • File Conflict

When opening the VBA Excel file, it gets conflicted with other programs.

  • Too Many Legend Entries

The Excel chart contains more legend entries than space available to display the legend entries on the chart.

  • Excel File Corruption

Your .xls files got corrupted, infected, or damaged.

Although many reasons would cause this Excel error 1004 problem, luckily, some valid methods can help users re-access the files. Let’s check them one by one.

Fix 1. Delete the GWXL97.XLA Files to Fix Runtime Error 1004 in Excel

The easiest method to fix the Excel error 1004 is to find and delete the error file.

Step 1. Go to C:Program FilesMS OfficeOfficeXLSTART.

Step 2. Find GWXL97.XLA file and delete it.

Step 3. Reopen your Excel file and check if the problem is solved.

Fix 2. Check the Trust Access to the VBA Project Object Model

Another solution you can try is to enable a VBA project trust option in Excel Trust Center. Follow the detailed steps and have a try.

Step 1. Open a blank Excel file and click «Files» on the upper left.

Step 2. Click Option and go to Trust Center.

Enter Excel Option

Step 3. Find and enter the Trust Center Settings.

Enter Trust Center Settings

Step 4. Under Macro Settings, tick the option of «Trust access to the VBA project object model.»

Trust Access to the VBA Project

Now you can check your Excel file.

Fix 3. Create Another Excel Template to Fix Runtime Error 1004 in Excel

This method could be a little bit complicated, but it’s useful and worth trying.

Step 1. Please start a new Excel workbook and make sure there is only one worksheet in it.

Step 2. Format the workbook first and then put the data you need onto it.

Step 3. Tap File > Save As, first enter the file name, and click the unfold arrow in Save as Type column.

Excel Save As

Excel 2003: Choose Excel 97-2003 Template.

Excel 2007 or Later: Choose Excel Template.

Choose the Right Template

Step 4. Click «Save» to confirm.

Now you can insert it programmatically by using the following code: Add Type:=pathfilename. The file name is the one you set when you create the new Excel template.

Fix 4. Repair Corrupted Excel Files Due to Error 1004 

If all the above solutions can’t help you out, then there is one possibility that the Excel file you want to open is damaged. To fix a damaged Excel file, you can rely on file repair software. EaseUS Data Recovery Wizard is a great choice.

With this tool, click the «Repair» button and wait for it to fix all the corrupted documents for you.

  • Repair various corrupted files, including repairing Word, Excel, and PDF document 
  • Fix unreadable contents in Word efficiently
  • Repair corrupted PDF files, extract the text, comments, labels, graphics, etc. 
  • Compatible with Microsoft Office 2019, 2016, 2013, 2010, & previous versions.

Download the software and follow the detailed steps below to fix corrupted Excel files.

Step 1. Launch EaseUS Data Recovery Wizard, and then scan disk with corrupted documents. This software enables you to fix damaged Word, Excel, PPT, and PDF files in same steps. 

select the disk with corrupted documents

Step 2. EaseUS data recovery and repair tool will scan for all lost and corrupted files. You can find the target files by file type or type the file name in the search box. 

find corrupted documents

Step 3. EaseUS Data Recovery Wizard can repair your damaged documents automatically. After file preview, you can click «Recover» to save the repaired Word, Excel, and PDF document files to a safe location.

repair corrrupt documents

The Bottom Line

After reading, you must have a thorough understanding of how to fix Runtime error 1004. If you can make sure that the Excel file you want to open is valid, then the first three methods would help you out.

Once you got a damaged Excel file, a professional file recovery tool is a wiser choice. EaseUS file repair software is highly recommended by many users & IT professionals to help you repair Word, Excel, PowerPoint, and PDF files. 

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

VBA Error 1004 in Excel

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

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

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

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

VBA 1004 Error

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

Top 6 Excel VBA 1004 Runtime Errors

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

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

This error occurs while renaming the sheet.

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

Look at the below code.

Code:

Sub Error1004_Example()

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

End Sub

VBA 1004 Error Example 1

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

VBA 1004 Error Example 1-2

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

VBA 1004 Error Example 1-1

So, try renaming the sheet accordingly.

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

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

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

VBA 1004 Error Example 2

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

Code:

Sub Error1004_Example()

  Range("Headings").Select

End Sub

VBA 1004 Error Example 2-1

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

VBA 1004 Error Example 2-2

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

Code:

Sub Error1004_Example()

  Range("Headngs").Select

End Sub

VBA 1004 Error Example 2-3

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

VBA 1004 Error Example 2-4

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

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

 Look at the below code.

Code:

Sub Error1004_Example()

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

End Sub

VBA 1004 Error Example 3

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

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

VBA 1004 Error Example 3-1

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

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

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

Look at the below code.

Code:

Sub Error1004_Example()

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

End Sub

Example 3-2

It will throw the below error.

Example 3-3

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

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

Now, take a look at the below code.

Code:

Sub Error1004_Example()

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

End Sub

Example 4

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

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

Example 4-1

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

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

Look at the below code.

Code:

Sub Error1004_Example()

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

End Sub

Example 5

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

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

Example 5-1

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

Recommended Articles

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

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

Понравилась статья? Поделить с друзьями:
  • Piron пароконвектомат коды ошибок
  • Piriform speccy сбой инициализации dll цп ошибка 2 будет отображаться не вся информация
  • Pipos error 26 file not found fallout new vegas как исправить
  • Pipeline error decode что это
  • Pipeline error decode как исправить на телевизоре