Excel crash after Copy and paste Chart image - excel

I Need to Copy an picture/image of a chart which is in another workbook (WbO), and paste the picture in a worksheet in this workbook (TWb), using Excel vba.
I figured out a simple code to do this.
The good thing is that the code works. Stepping line by line throught the code everything completes perfectly.
However, if I run the code (no Stepping) it also runs until the end without any error and completes the job. BUT, by the end Excel Crashes without any error message, restarts and reopens the workbook. (all work lost).
The weirdiest thing is that it crashes 3 to 5 seconds after ending the run. 3 to 5 seconds is an enormous lenght of time for computing. What is it doing during this time??
For testing, I added a 'Msgbox "Completed", vbokonly' as last code line. This made vba stop and show the message, and no crash while the message is on screen. Clicking ok, the macro runs to the end and then, after some seconds ... Crash.
Searched for similar problems in the web and found some old posts refering errors related to copy/paste, but no complete crash like this.
Tried this same file/code in different PCs, both with up-to-date office 365 but different update channels (not same build). The result was exactly the same.
Tried changing the .CopyPicture statement to a normal Copy, and then using PasteSpecial as Picture. Same Result.
Even tried moving the copy/Paste instructions to different subs (suggestion from a 2018 post), and inserting DoEvents in between .. without any luck.
Does someone have a clue why this is hapenning?
How to overcome this issue?
Help welcomed
Sample code below:
Application.EnableEvents= False
Set WbO = /Workbooks.Open("WbOFileName",0)
Set ChrtObj= Worksheets("MyCharts").ChartObjects(1) 'Set handle to the Chart obj
TWb.Activate ' Activate destination Workbook = The Wb which contains the macro
ChrtObj.CopyPicture
RangeToPasteOn(1,1).Select ' Select Top-Left cell to paste the Chart on
ActiveSheet.paste ' Paste the Chart
' ... here Code to ajust Size and position to fit destination range
Application.CutCopyMode = False
Set ChartObj = Nothing 'Release handle
WbO.Close
Set WbO = Nothing
Application.EnableEvents= True

Related

Copying Editable Excel chart to Word Error 4605

I have a macro that is intended to copy a chart from excel into a word document in the same way as manually copy and pasting using "Keep Source Formatting and Embed Workbook." Below is the code that, to my understanding, should accomplish this.
Set reductionChart = graphWorksheet.ChartObjects("reduction")
reductionChart.Copy
masterReport.Paragraphs.Last.Range.PasteAndFormat wdChart
graphWorksheet is the worksheet that contains the graphs, masterReport is the word document.
The issue I am having is error 4605 command not available on the PasteAndFormat line. I happened to discover that manually copying the graph then running the line worked without issue. Thinking that maybe right clicking copied in a different way than .copy so I record a macro of the action and ended up with:
ActiveSheet.ChartObjects("Reduction").Activate
ActiveChart.ChartArea.Copy
Even substituting this in the error still occurs. What is happening here?
After some additional testing I am thinking that possibly when using .copy the chart is sort of only stored within excel and not the clipboard so when paste and format looks for something it see an empty clipboard and has an error, but right clicking copy stores it to the clipboard hence why is available still even after I run ActiveChart.ChartArea.Copy again.
I've attempted to create new workbook with a single sheet and chart. Also tried using late binding instead on the off chance that did something. This is the full code still giving the same issue
Sub test()
Dim masterWord As Object
Dim masterReport As Object
Set masterWord = CreateObject("Word.Application")
Set masterReport = masterWord.Documents.Add
masterWord.Visible = True
ThisWorkbook.Worksheets(1).ChartObjects("Chart 1").Copy
masterReport.Paragraphs.last.Range.PasteAndFormat wdChart
End Sub
After much testing this is the best workaround I'm managed to figure out.
reductionChart.Chart.ChartArea.Copy
masterReport.Paragraphs.Last.Range.PasteAndFormat wdFormatOriginalFormatting
masterReport.InlineShapes(masterReport.InlineShapes.Count).LinkFormat.BreakLink
wdFormatOriginalFormatting and wdPasteDefault both work and don't seem to make a difference to the outcome as far as I have seen.
This has one issue that I've found which is that on ActiveDocument.Fields.Update an information box will popup warning that the linked file is unavailable. This will occur for each unlinked item. I attempted to use Application.DisplayAlerts = False but this did not prevent the popup. This may come back to bite me, but I simply removed this line as it was unnecessary for my purposes.

How to Loop Through ActiveX Checkboxes on VBA

I'm actually trying to make a userform that controls every checkbox in the Workbook Sheets (it's mostly graphs that shows the data from a specific period for the Company), since every graph has the same checkboxes (ActiveX ones) with the same names on them I though about making a Userform that is always active and in this way the client can just select which ones he will use and it would just loop through the other sheets without a problem.
But here is the problem first of all my code:
Dim ws As Worksheet
If Me.CheckBox1.Value = True Then
For Each ws In ThisWorkbook.Worksheets
ws.OLEObjects("chkAno1").Object.Value = 1
Next ws
ElseIf Me.CheckBox1.Value = False Then
For Each ws In ThisWorkbook.Worksheets
ws.OLEObjects("chkAno1").Object.Value = 0
Next ws
End If
I did it with only one checkbox to test it out (There is a "chkAno1" in every sheet that I want to affect) but everytime I run the code and click the checkbox I get " Error 1004: The Method "OLEObjects" from object "_Worksheet" Failed", and what's weird is that If I change "ws" with "ActiveSheet" the code works fine, but only updates the currently open sheet.
So I'm at a loss right now.
thanks for your help. I found out the problem, there was some sheets without any Checkboxes on them, so the Code kept giving me the error.
The solution I found for it was to put On Error Resume Next at the beggining and it worked like a charm! (I actually needed to put it on the graphs as well)
But in the end I ended up reworking the code to affect directly the Graph using ws.ChartObjects("grafico").Chart.FullSeriesCollection(1).IsFiltered = True instead of ws.OLEObjects("chkAno1").Object.Value = 1 Because at the end the process of updating every checkbox and after that all the charts would be actually really slow on some older computers and updating directly the Graph showed a great increase in speed.
Thanks to everyone that Commented and I hope the solution I found can help someone else!

What is the best way to paste excel ranges as pictures into ppt

I've got a macro that opens a ppt template file and populates slides with the contents of pivot table, pasting these as enhanced metadata - pretty straight forward job - filter pivot using a criteria, copy range, paste special with DataType:=2.
The issue is that I've got this process as a loop that does the job of opening ppt template, populating slides with these images and saving as a copy 10 times (producing 10 files) and at random I get this error:
"Run-time error '-2147188160 (80048240)':
Shapes.PasteSpecial : Invalid request. Clipboard is empty or contains
data which may not be pasted here."
Now the problem with this error is that it's not true, because all I have to do is click RUN and the macro then proceeds with no issue without me changing a single thing. And it may run with no issues for a couple of times and then throw an error at random - the loop iteration, the pivot table range copied and the slide number are all inconsistent.
What I assume is the problem is the memory, hence my question - is there a better way to copy excel range and paste as image into ppt file?
My code at the moment is very simple:
ws.PivotTables("pivot").TableRange2.Copy
MySlide.Shapes.PasteSpecial DataType:=2
Maybe this method is inefficient? Will changing the DataType help? (I assumed not, since the issue is with clipboard) Unfortunately it's quite hard to find materials on controlling ppt's through excel vba
When pasting, it's likely that the process of copying the object to the clipboard hasn't finished. And so it's not available for pasting.
One way to deal with this might be to set up two simple separate routines. One routine to do the copying, and the other one to do the pasting.
In doing it this way, it may force VBA to wait until one process is finished before moving onto the next one.
Here's the routine to copy the range...
Sub CopyPivotTableRangeToClipboard(ByVal target As Range)
target.Copy
End Sub
Here's the routine to paste the range into the slide...
Sub PasteRangeIntoSlide(ByVal theSlide As Object)
theSlide.Shapes.PasteSpecial DataType:=2
End Sub
Then you would call these procedures as follows...
CopyPivotTableRangeToClipboard ws.PivotTables("pivot").TableRange2
PasteRangeIntoSlide MySlide
EDIT
If separating the copy and paste processing into two separate procedures doesn't help, you can additionally try pausing the macro for 1, 2, or 3 seconds, along with calling DoEvents, after each process. For this we can use the following procedure...
Sub PauseMacro(ByVal seconds_to_wait As Integer)
Dim start_time As Single
start_time = Timer
Do
DoEvents
Loop Until Timer - start_time > seconds_to_wait
End Sub
Now your code would be as follows...
CopyPivotTableRangeToClipboard ws.PivotTables("pivot").TableRange2
PauseMacro 3 'seconds to wait (change as desired)
PasteRangeIntoSlide MySlide
PauseMacro 3 'seconds to wait (change as desired)

Unexpected results from a Worksheet.Activate event

I’m running excel 2010 on windows 7.
The following macro does what you would expect, ie (1) inserts a new worksheet, (2) adds a rectangle, and (3) activates cell A1.
Sub addSheetAndButton()
Dim buttonSheet As Worksheet
Set buttonSheet = ThisWorkbook.Sheets.Add
buttonSheet.Shapes.AddShape(msoShapeRectangle, 100, 100, 100, 50).Select
buttonSheet.Range("A1").Activate
End Sub
My problem is when I try to run it with a Worksheet.Activate event, for example:
Private Sub Worksheet_Activate()
Call addSheetAndButton
End Sub
This time (1) a new worksheet is not inserted, (2) the rectangle is added to the worksheet associated with the activate event, (3) cell A1 is not activated and (4) the rectangle remains activated.
What am I doing wrong? Any help would be greatly appreciated.
Thanks very much for trying this. I’m sorry it has taken me a while to get back, but I’ve been experimenting with this. I have discovered that when I exit and restart Excel, the addSheetAndButton macro works as expected under the Worksheet.Activate event. However, I have a different macro that uses another Worksheet.Activate event to update some charts. On what seemed to be a random basis, this would create a “run time error 6” - an overflow that resulted from trying to assign an out of bounds value to a variable.
I never got this error if I bypassed the Worksheet.Activate event/macro and ran the chart update macro by hand. After resetting VBA/Excel from the “run time error 6”, the addSheetAndButton macro behaved exactly as I described in my original post. The only way to cure it was to exit and restart Excel.
I think (hope) that I have traced the source of the run time error back to a line in my chart update macro where I had selected rather than activated a worksheet before reading data from it – though I am surprised at the result. It is worth pointing out that once Excel entered the “not as expected” state, the on-screen message from the following two lines was the name of the previous active sheet and not “Sheet1”.
Worksheets(“Sheet1”).Activate
Msgbox ActiveSheet.Name
Again, the only apparent way to cure this was to exit and restart Excel.
Thanks again for your help.

Problem with adding event code to newly created sheet

I have a problem with adding an event code to a newly created sheet.
The problem seems to only occur right after I open the Excel workbook.
I use
Dim codemod As Object
codemod = ActiveWorkbook.VBProject.VBComponents(Worksheets("Sheet4").CodeName).CodeModule
to add the code to the created sheet module but when I try to run this code right after opening the Excel workbook it gives me an error: run-time error '9' Subscript out of range. The debug points to the codemod line.
The weird part is that this error does not come up again when I change the code just a tiny bit and then change it back to the original state. After I do this the code runs as it should i.e. inserts code to the newly created sheet.
Anyone got any idea what may be the problem?
There is not much else to the code except inserting the lines but that does not seem to be the problem.
Thanks in advance
(This is my first action on S.O. so please don't shout at me when I'm doing things wrong.)
Did you concider preparing a workbook + sheet with the desired event code (Test1.xls-Sheet1). Then, in the target workbook (Test2.xls), copy that prepared sheet. The code in the target workbook would look like
Sub Demo1()
Workbooks.Open "Test1.xls"
Sheets("Sheet1").Copy After:=Workbooks("Test2.xls"). _
Sheets(Workbooks("Test2.xls").Worksheets.Count)
Workbooks("Test2.xls").Activate
End Sub
This obviously is a workaround but it works instantly.
A second option could be to prepare the 'workbook-with-one-sheet' and save it as a (sheet) template in D:\Documents and Settings\User\Application Data\Microsoft\Excel\XLSTART. In that case the code can be
Sub Demo2()
Sheets.Add Type:="Test1"
End Sub

Resources