Sheet inaccessible to macro: Error 1004: Application/Object Defined Error - vba

This is happening in several of my macros, but this is the one in from of me:
Private Sub resettool()
'''resets step 2 input and user input on MPP tabs
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Call showsheets 'makes all of these sheets .Visible = True
'clear data from lookups and data corrals
Sheets("Media by Copy Lookup").Range("b1",Range("b1").End(xlToRight).End(xlDown)).ClearContents
Sheets("Total Media Lookup").Range("d1",Range("d1").End(xlToRight).End(xlDown)).ClearContents
Sheets("Total Media Lookup").Range("b2:c100").ClearContents
Sheets("Media by Copy Data").Range("a1",Range("a1").End(xlToRight).End(xlDown)).ClearContents
'etc etc
End Sub
It continues with similar data-clearing lines for a while. This started happening when I took someone else's code and cleaned it by removing the .Select usages as people on here have suggested. It seems that the macro isn't able to access the sheets I'm referencing, because a line runs successfully if I step into the code, manually select the referenced sheet, and then hit go (but then of course I get the same error when I try to edit another sheet).
Any ideas why the macro wouldn't be able to access these sheets unless I explicitly activate/select them? The sheets are all visible, so that shouldn't be the problem.
P.S. I've seen the guide on using .Rows.Count).End(xlUp) instead of End(xlDown) to find the bottom of my data and will implement that soon, but this issue is occurring no matter how I define the range; it's about the sheet.

Related

Excel Crashes after but not while running macro to copy formatting of chart to another chart

I wrote a macro that copies the format of one chart object and pastes it into other chart objects. The macro SUCCESSFULLY completes and the newly made chart objects are correctly made. It does what it's supposed to! However, Excel crashes immediately upon saving or after fiddling with the new chart object. It crashes in both Excel 2010 and Excel 2016.
I have isolated the code snippet that causes the Excel crash. In the following snippet of code, if Lines 8-9 are commented out, Excel does not crash:
For Each cht In sh_plots.ChartObjects
With cht.Chart
'copies master chart format
master_plot.Chart.ChartArea.Copy
'applies formats
.ChartArea.Select
ActiveSheet.PasteSpecial Format:=2
Application.CutCopyMode = False
So these 2 lines (8-9) are the ones at fault:
.ChartArea.Select
ActiveSheet.PasteSpecial Format:=2
Does anyone know why these 2 lines are acting as the bane of my existence right now? I have tested these 2 lines multiple times, and the crash is reproducible. My excel file is not corrupt because I tried to copy the code as text to a new Excel file and used safe mode etc etc, still crashing.
I do not want to have to copy the master chart property by property to accomplish the same thing as this simple format paster - unless someone has a better idea, that would require so much more extra code!
I have the Event Viewer error log if that would shed any light. Thanks!
Untested, as am on mobile. But I don't think you need to activate/select to copy-paste.
Code below toggles events and screen updating.
' Ensure you have Option Explicit and have declared cht as a ChartObject '
With application
.screenupdating = false
.enableevents = false
End with
'copies master chart format
master_plot.Chart.ChartArea.Copy
For Each cht In sh_plots.ChartObjects
'applies formats
Cht.chart.paste type:=xlformats
Next cht
'reset property outside of loop - once all done. '
Application.CutCopyMode = False
With application
.screenupdating = true
.enableevents = true
End with
Oh I solved the problem by messing around with more stuff!
For some reason Excel crashes if you specify error bars before pasting the chart format. So I did not specify error bars until after I pasted the format. Really weird that it does this.

VBA deleting a duplicate copy of chart object fails in Excel 2013

I have a VBA code that is intended to copy the contents of a range into a chart, to be able to export it to a PNG file (+some post-processing using an external command). Here is the relevant part:
Sub GenererImage() ' Entry point
getparams ' Collect parameters and define global variables
MiseEnPage.Range(ZoneImage).CopyPicture Appearance:=xlScreen,Format:=xlPicture
Application.DisplayAlerts = False
With ObjetGraphique.Duplicate
.Chart.Paste
.Chart.Export Filename:=CheminImage, Filtername:="PNG"
.Select
.Delete
End With
Application.DisplayAlerts = True
End Sub
The getparams procedure called in there is just collecting some parameters from another worksheet to define:
"MiseEnPage": reference to the worksheet object where the range I want to copy exists,
"ZoneImage" is set to the "B4:F11" string (refers to the range address),
"ObjetGraphique" is a reference to a ChartObject inside the "MiseEnPage" sheet. This ChartObject is an empty container (I am mainly using it to easily set the width and height).
"CheminImage" is a string containing the path to the picture filename on disk.
This code used to work perfectly in Excel 2010. Now my company has deployed Excel 2013 and my code now fails on the .Delete line, leaving the copy of the ChartObject (with the range picture pasted inside it) on the sheet and stopping macro execution.
I have tried activating the worksheet first, selecting the duplicate prior to deleting it and other things, to no avail. When tracing the execution in the debugger it chokes on the delete line with error 1004.
I am frustratingly stuck. Any clue?
If this works
With ObjetGraphique.Duplicate
.Chart.Paste
.Chart.Export Filename:=CheminImage, Filtername:="PNG"
.Select
End With
Selection.Delete
we have to assume that either the With is holding a reference and preventing the delete, or that the delete routine called by the selection object is not the same delete that's called by ObjetGraphique.Duplicate.delete, or that it's a subtle timing bug and that the extra time it takes to retrieve the selected object is enough to fix it.
OK after fiddling a lot with the object model, here is (the relevant part of) my final solution. Many thanks to HarassedDad for the clues.
Sub GenererImage() ' Point d'entrée
getparams
MiseEnPage.Range(ZoneImage).CopyPicture Appearance:=xlScreen, Format:=xlPicture
Application.DisplayAlerts = False
With ObjetGraphique
.Chart.Paste
.Chart.Export filename:=CheminImage, Filtername:="PNG"
.Chart.Shapes(1).Delete
End With
Application.DisplayAlerts = True
End Sub
What seems to happen is that the .Paste method of the Chart object creates a Shape in the .Shapes collection of this object. I can delete this Shape, but not the Chart itself or the ChartObject. Excel 2010 would allow that, but not Excel 2013.
I still do not understand the reasons, but at least I have something that works (until the next excel update probably...).

Excel 2013 crashes when unhiding columns

I've spent hours trying to figure this out with no solution being found so far. I have a macro (see below) that unhides/hides a range on a spreadsheet. Seems simple enough and the first two times I run this macro it works fine; however, the third time, which is always unhiding the range, usually causes Excel 2013 to crash. I read here that having an volatile user defined function in the range I'm unhiding might be causing the problem, but I already tried making the function not volatile and Excel still crashed. Does anyone have any ideas or experienced this before?
Sub HideShowSQLCreator(control As IRibbonControl)
Dim SQL_Creator As Range
Dim Report_Home_Cell As Range
Set SQL_Creator = Sheets("Report").Range("SQL_Creator")
Set Report_Home_Cell = Sheets("Report").Range("Report_Home_Cell")
If SQL_Creator.EntireColumn.Hidden = False Then
SQL_Creator.EntireColumn.Hidden = True
Report_Home_Cell.EntireRow.Select
ActiveWindow.FreezePanes = True
ActiveSheet.Range("Report_Home_Cell").Select
Exit Sub
End If
If SQL_Creator.EntireColumn.Hidden = True Then
SQL_Creator.EntireColumn.Hidden = False
ActiveWindow.FreezePanes = False
SQL_Creator.Select
Exit Sub
End If
End Sub
So, I got frustrated and figured the workbook was just corrupted so I created a new one from scratch. The macro was working fine until I got to the end and realized that the crash had to do with a big pivot table to the right of the range I was trying to hide/unhide. I'm not sure why it happened, but my solution was to just put the columns I was trying to hide/unhide in a separate sheet in the workbook. The macro works fine with them in separate sheets. Weird stuff, but I'm glad there was a solution in the end.

Closing a userform that is in workbook A from workbook B

I'm new to VBA so there might be a simple answer to this question but if there is I sure haven't found it. What I am doing is copying data from several workbooks into one master workbook. I have writen the code for this and it works fine. The only problem is the workbooks where I'm retriving the data have userforms that automatically initiate when the workbook is accesed. This means that when I run my code to copy the data it hangs at each userform and wont continue until I've physically closed each userform. So my question is: Is there a way to remotely close the userforms in the raw data workbooks from my master workbook VBA code? Thanks in advance.
to close all userforms, (if you want a specific one , change my code)
sub Close_Userforms()
Dim Form as VBA.Userform 'if not work change to Object
For each Form in VBA.Userform
'can add a condition, like : if Form.name ="Whatever" then
unload Form 'if you don't want to lose the data from the userforms, Form.Hide, and later re-loop and Form.Show
next Form
edit : can also if Typename (Form)="Whatever" then , for the condition
Assuming you mean that the forms pop up when you open the workbooks, disable events before doing so:
Application.Enableevents = False
Workbooks.Open ...
Application.Enableevents = True
for example.
I would suggest trying
Application.EnableEvents = False
Further reading.
Short description: All events (Workbook_Open, Workbook_BeforeSave etc), that usually fires upon opening or closing a workbook, will be ignored.
I have written the following functions to make all macros a bit simpler (and faster). Simply place these functions in a regular module.
Public Function CalcOff()
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Application.EnableEvents = False
End Function
Public Function CalcOn()
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.EnableEvents = True
End Function
Begin your macro with:
CalcOff
And then end your macro with:
CalcOn
Remember that you need to put "CalcOn" in all places that exits the running macro.
Disabling ScreenUpdating makes the code "run in background" (nothing will be displayed).
Setting Calculation to manual improves the speed of the code, since no calculations will be made when changing data. But it's very important to exit all macros with "CalcOn", otherwise your sheet won't calculate (and that's not funny), and it will look like Excel has frozen (since ScreenUpdating would still be turned off).
However, if you by any chance happen to break a running code without exiting it the proper way (running "CalcOn"), simply close the Excel application and reopen it. Or run a macro that ends with the "CalcOn" code. Or create a new macro with that simple line.

Copy method fail due to memory

In my workbook, I copy the current sheet to keep as a record of a sale. Eventually, the workbook fills up with sales and at some point throws an error when I try to copy another sheet. After saving, then completely exiting Excel, then reloading the file, I can continue without problems. I'm guessing it's a memory issue, but I'm not quite sure how to solve it without restarting Excel. I can't remember the wording of the error exactly, but it went along the lines of "Copy method of worksheet failed". FWIW I use "Application.CutCopyMode = False" at the end of the macro that copies the sheet.
1st edit:
I'd like to post all of the code, but there's just so much of it (mostly not related to updating values, input verification, etc. etc.); if I post everything, I'd have to post all of the other functions for it to make sense. Suffice it to say, here's what I think is applicable:
ActiveSheet.Copy After:=Sheets(3)
...(more code)...
Call resetInterface(True, True, (wasScreenUpdating), (wasProtected))
and for the "resetInterface" function:
' Final operations for a typical function/sub '
Function resetInterface(Optional calc As Boolean = False, Optional ccmode As Boolean = False, Optional scrUpdate As Boolean = True, Optional protectWS As Boolean = False)
With Application
If calc Then
.Calculation = xlCalculationAutomatic
.Calculate
End If
If ccmode Then .CutCopyMode = False
.ScreenUpdating = scrUpdate
End With
If protectWS Then ActiveSheet.Protect
End Function
There used to be a problem when copying sheets in Excel that the CodeName property of the Worksheet object would be appended with a 1 and get to be too long. I think it's been fixed, but it would depend on what version you're using.
Open the VBA (Alt+F11) and show the Project Explorer (Ctl+R). Look at the CodeNames of your copied sheets. Are they Sheet1, Sheet2, etc..? Or are they Sheet1, Sheet11, Sheet111, etc...? If the latter, this may be causing the problem. See http://support.microsoft.com/kb/177634
Or it could be that you have a workbook level name, see http://support.microsoft.com/?kbid=210684
The error you're referring to is:
Excel VB run-time error 1004: "Copy method of Worksheet class Failed"
Can you post the macro you've written?