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.
Related
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
I'm currently using a code to update a file with a loop running through multiple sheets. Up until now, the code ran smoothly. On today's run, I encountered "run-time error '-2147319767 (80028029)' Automation error, Invalid forward reference, or reference to uncompiled type."
The error occurs on the line Workbooks("Upload.xlsm").Worksheets(branchName).Range("C7").PasteSpecial Paste:=xlPasteValues and presents itself on the 6th iteration of the loop.
I used On Error Resume Next as a temporary measure to complete the run as it was imperative to have it done at that time.
Upon completion, 3 of the iterations had failed (sixth, seventh and tenth). The three had no correlation to one another (i.e. different copy sources, values, etc) but had other iterations with the exact same copy source/values which completed successfully.
Running another copy command at a later time onto these sheets resulted in the same error. I eventually had to delete and recreate the sheet to resolve the error.
' Uploads file update
fpath = Workbooks("TEG Rates.xlsm").Worksheets("Link List").Range("E3").Value
Workbooks.Open fpath & "Upload.xlsm"
For branchNo = 21 To 37
branchName = Workbooks("TEG Rates.xlsm").Worksheets("Link List").Range("A" & branchNo).Value
branchGroup = Workbooks("TEG Rates.xlsm").Worksheets("Link List").Range("B" & branchNo).Value
' Copy/Paste Buy & Sell
Workbooks("TEG Rates.xlsm").Worksheets(branchGroup).Range("D7:G111").Copy
Workbooks("Upload.xlsm").Worksheets(branchName).Range("C7").PasteSpecial Paste:=xlPasteValues
For no = 7 To 10
Workbooks("Upload.xlsm").Worksheets(branchName).Range("D" & no).Value = "=ROUND(100/C" & no & ",6)"
Next no
Workbooks("Upload.xlsm").Worksheets(branchName).Range("D14").Value = "=ROUND(100/C14,6)"
Workbooks("Upload.xlsm").Worksheets(branchName).Range("D15").Value = "=ROUND(10000/C15,4)"
Workbooks("Upload.xlsm").Worksheets(branchName).Range("D16").Value = "=ROUND(100/C16,6)"
Workbooks("Upload.xlsm").Worksheets(branchName).Range("D19").Value = "=ROUND(100/C19,6)"
Next branchNo
Workbooks("Upload.xlsm").Close SaveChanges:=True
Application.CutCopyMode = False
While currently I am able to operate this code, my concern is that my team will encounter this whilst I'm away. What could have caused this/what can I do to prevent this from occurring? I'd be willing to provide the files if required.
My friend and I had the same issue. I enabled the "AccessibilitycplAdmin 1.0 type admin" under Tools > References (within the VBA editor), that fixed the issue in both computers
I had the same issue with a macro today.
Noticed that the error popped up when selecting a sheet using Sheets(sheet_name_var).Select.
A workaround that I've found is:
- Make a copy of the sheet the macro was having problems with,
- Delete the original sheet,
- Rename the copy to the original name.
Hope this helps.
I was having the same error caused by an issue that was potentially related, and it was helpful to create a worksheet object rather than referencing a sheet within a workbook all in one step. So, instead of:
Workbooks("Upload.xlsm").Worksheets(branchName).Range("C7").PasteSpecial
You could instead try:
Dim xlWB as Excel.Workbook
Dim xlWS as Excel.Worksheet
Dim xlRange as Excel.Range
Set xlWB = Workbooks("Upload.xlsm")
Set xlWS = xlWB.Worksheets(branchname)
Set xlRange = xlWS.Range("C7")
xlRange.PasteSpecial Paste:=xlPasteValues
Sometimes it's beneficial to break up the steps, even though it is doing the same thing.
The only way I found to solve it was:
Change the property "Load To" for all query results in the damaged Sheet to "Only Create Connection".
Make a copy of the Sheet
Delete the damaged Sheet
Rename the just created Sheet to the name of the damaged one
Change all the query results to the new Sheet in the same original location
I hope this helps.
I had a very similar issue, I have several similar excel files, all with the same code. The code ran in all excels but one, with the same error:
"run-time error '-2147319767 (80028029)' Automation error, Invalid forward reference, or reference to uncompiled type."
I was able to solve the problem by saving the corrupt excel as .xlsx instead of .xlsm, closing all excel applications, reopen the .xlsx, add the code and save as .xlsm. Now it is working...
Exactly same thing happened to me. But with a little bit more serious consequences as my dashboard was already in production.
It was really shocking as code as running smoothly just 5 mins earlier.
Here's the changes that I made -
Conditional formatting
Pivot table updates - major formatting updates
I believe some weird combination of conditional formatting over pivot table might have caused this issue.
One peculiar symptom associated with this corrupted workbook/sheet as that I was unable to see any macro in the dialogue while I was trying to assign a macro to the button.
The dialogue box was empty ! not listing any macros from any module/form/worksheet.
Tried -
Removing pivot table
Resetting formatting
Removing conditional formatting
Restarting excel
Restarting system
None of the above worked !
Next solution, as suggested by Horacio, is to duplicate and delete the corrupted sheet.
This immediately solved the issue.
Similar problem - same error. The sheet is the results of a query "Load To" table. Followed the idea from https://stackoverflow.com/users/13737858/horacio-cano. Changed "Load to" from table to Connection only; deleted the sheet; changed "Load to" to new table; refreshed query. Macro runs without error.
I solved this by removing the reference to Microsoft Scripting Runtime in Tools>References selecting "Ok" and then re-adding it again.
(Not the exactly the same situation as posted by the OP, but the same error message:)
I got the same error message while trying to delete an ActiveX element in a UserForm.
Turns out that I still had (another) user form open as a modal window in the Excel app (which was in the background because I was trying to edit it the Visual Basic Editor).
Simply closing the user form solved the issue.
Not really an answer, but my 2 cents on the matter (a comment could not fit it :))
I found that the underlaying error comes from .NET:
Exception Source: mscorlib
Exception Type: System.Runtime.InteropServices.COMException
Exception Message: Invalid forward reference, or reference to uncompiled type. (Exception from HRESULT: 0x80028029 (TYPE_E_INVALIDSTATE))
Exception Target Site: InvokeDispMethod
With that, I found that this page:
https://developercommunity.visualstudio.com/t/live-code-analysis-causes-compiler-errors-in-code/599442
System.Runtime.InteropServices.COMException : A reference to the component 'MyProjectReference' already exists in the project.
at VSLangProj.References.AddProject(Project pProject)
So it appears the error is linked to some cached file(s) used internally and language stuff.
Now if you look here : What does 'Cor' stand for?
MSCorLib.dll officially became the acronym for Multilanguage Standard
Common Object Runtime Library.
If you finally add in the mix that I was manupulating files in Excel while changing the UI Language in settings just before I got a corrupted file with the same error that the OP mentions, I would guess the error definitely has some thing to do it!...
I am trying to copy some charts (embedded) in different worksheets of an excel workbook using vbscript into different slides of a powerpoint. I would like to keep the link between the excel sheet and the powerpoint while doing so and therefore I used the below piece of code that allows me to keep formatting and link (instead of a simple paste or PasteSpeical. Is there any other way?) :
For i = 1 to TotalNumWorkSheets 'I iterated with indices.
Set pptSlide = pptPres.Slides.Add(i, 11) 'There is one opening slide before this.
set ws = wb.Worksheets(i)
ws.ChartObjects(1).Chart.ChartArea.Copy
pptApp.CommandBars.ExecuteMso("PasteExcelChartSourceFormatting")
pptApp.CommandBars.ReleaseFocus
With pptSlide
.Shapes.Title.TextFrame.TextRange.Text = objCurSheet.Name
'Adding some more textboxes here. Working fine. Position checks out in PPT.
.Shapes(.Shapes.Count).Left = 20 'Doesn't work for all slides.
End With
Next
The code works and copies all the charts, creates titles, adds new text as expected, but I am not able to position the charts on individual slides because after the ExecuteMso command, I don't know how to access the reference to the chart. I read in one of the SO posts that pasting using this method looses the chart selection but you can access the last .Shapes object since pasting always adds the object to the end of the list. Is that always the case? I tried accessing and positioning my chart by accessing the last object but it only works for the first slide of the loop (i.e. the first chart pasted is shifted to Left=20). The rest all charts in other slides are centered. Can someone explain where and how to add the formatting chart options? I ran into an even weirder problem. If I increase the number of worksheets, even the first plot looses it's Left formatting. The above code is the only place where I add formatting so I don't know what is happening. I am sure I am not formatting it correctly.
Many thanks for your suggestions.
Edit: One additional thing which I tested. I am using
WScript.Sleep 500
code before the For loop ends since it gives enough time for earlier operations to finish (at least that's what I understood from many other google searches).
So after some more searching and testing, I found a solution (for my case at least).
Moved the WScript.Sleep 1000 (500 didn't work for me) statement just below CommandBars.ReleaseFocus.
It makes some sense now since it is the Chart copying, pasting and linking from excel that needs time. Especially with source formatting. After that there is only text generation which I believe is not so heavy.
Cleared all the set Object variables when not used. Especially the ones associated with the "With" keyword.
set obj = CreateObject()
With obj
'Do something here.
End With
set obj = Nothing
Not clearing them, apparently, can also prevent you from closing the applications even after you use the .Close and .Quit method. At least that's what I observed. I found PowerPoint.exe running in the task manager when nothing was opened.
After doing the above, I am able to copy with format the charts and also able to set the position of the charts. The weird problem of larger number of worksheets also disappeared. Hopefully, it might help others. If someone thinks the observations are incorrect or troublesome, please correct.
Just to let you all know, I'm a beginner to VBA and I'm using Excel and PowerPoint 2013.
The aim: I'm writing code in Excel VBA to paste a chart from Excel into PowerPoint. Then when it's pasted, move it to a set place within the slide.
The code I used: The framework of the code I started with is in http://peltiertech.com/Excel/XL_PPT.html#chartppt, the part called 'Paste the Active Excel Chart into the Active PowerPoint Slide (Early Binding)'.
The main difference is around the 'Paste' part, this is instead a 'PasteSpecial' and my code is as follows:
.
Charty.CopyPicture
ppApp.ActivePresentation.Slides(SlideNumber).Shapes.PasteSpecial (ppPasteEnhancedMetafile)
' Setting the correct position on the slide
ppApp.ActiveWindow.Selection.ShapeRange.Top = ChartTop
ppApp.ActiveWindow.Selection.ShapeRange.Left = ChartLeft
(Note. ChartTop and ChartLeft have been defined earlier)
The issues: I'm aware that after the PasteSpecial it doesn't have a select statement. However, (1) When I run the above code I get a runtime error '-2147188160' saying the Selection.ShapeRange is an invalid request (in the 'ChartTop' line), ie. it isn't selected so it can't be moved. (2) When I add a select statement to the 'Paste.Special' line I get an 'Object required' error on the new 'PasteSpecial' line, ie. it doesn't recognise it as a paste select statement.
The odd part: When I run the same macro on other people's computers using the exact same Excel and PowerPoint files it works (without the select statement in the 'PasteSpecial' line). I've looked at 'Tools' => 'References', and both of our computer have the same settings.
The questions: Is there a setting that I have overlooked on my computer which prevents the code from working? Is there a way after I've pasted it to reselect it before it is moved (I should tell you that the macro is to paste in many graphs into ppt simultaneously)? How come for other people at my work it works on their computers without the 'select' part of the PasteSpecial statement? How come when I use the Shapes.PasteSpecial (ppPasteEnhancedMetafile).Select statement, it doesn't recognise it as an object?
I hope that's clear.
Thanks in advance.
Dim oSh as Shape
Set oSh = ppApp.ActivePresentation.Slides(SlideNumber).Shapes.PasteSpecial (ppPasteEnhancedMetafile)(1)
Now you don't need to select anything (which is best avoided whenever possible). Just manipulate the pasted shape, oSh, directly.
The curious syntax (the (1) at the end) is because Shapes.Paste or .PasteSpecial returns a shaperange, not a shape; the (1) causes it to assign the first shape in the range to the oSh variable. Since there's only one shape in the range, that suits us just fine.
I have the following code that works in all other circumstances except in a single where it returns the error Can't move focus because it is invisible, not enable, or type that does not accept focus. The data in sheet consists only basic numbers and words. My objective is to select a range from one work book and paste it to another. It appear that excel does not recognise anything to be in the cells, although there in fact is. Does anyone know why this may be happening?
Set Users = Application.Workbooks.Open(PathA)
With Prices
.Sheets("Sheet").Range("A:AJ").Select
Selection.Copy
End With
'Set Risk = Application.Workbooks.Open(PathX)
With Risk
.Sheets("Sheet").Range("A1:AJ1048576").PasteSpecial Paste:=xlPasteAll
.Save
' .Close
End With
Users.Close
it looks like someone else had the same issue and was able to resolve it on an MSDN forum
http://social.msdn.microsoft.com/Forums/office/en-US/3263b079-7e4f-452c-8dcc-92c682b8370b/excel-form-cant-move-focus-to-the-control-because-it-is-invisible-not-enabled-or-of-a-type-that?forum=exceldev
maybe this fix will apply to your situation too.
... OK so on that page, one guy has a kludge that seemed to work for him:
Error was:
Can't move focus to the control because it is invisible, not enabled, or of a type that does not accept the focus.
How to Fix
1. Select the object with the problem, e.g. the Form or Control.
2. In the properties windows, select the name of the object and rename adding an "x" to the end, e.g. Rename CPanel to CPanelx.
3. Save the Form.
4.Now rename the CPanelx back to CPanel.
5. Run your form.
6. Problem solved.
Something screwy with Excel VBA, not sure what !, but this will get you working again.
Steve D.
and then someone else described the underlying problem, but his solution involved using design mode, which seems like it is maybe defeating the purpose of automating in vba, but the moderator seemed to like his answer better, so here that is as well
In normal use activeX controls are intended only to be activated, not selected, there's a difference. If you partifcularly want to Select the control (manually or with code), try putting Excel into Design mode first.
See also the topic "Why can't I select form and ActiveX controls?" in Excel's help (not VBA's help)
Peter Thornton
"Run-time error '-2147352565 (8002000b)': Can't move focus to the control because it is invisible, not enabled or of a type that does not accept the focus" Can be overcome but sequentially defining the area you wish to select. Obviously some may do this in any case, but it this specific instance it is needed to overcome the issue. This is an example for copying from one workbook to another and pasting where U is the sheet excel finds to be "invisible".
Dim U As Workbook
Dim Us As Worksheet
Set U = Application.Workbooks.Open(Path)
Set Us = U.Worksheets("sheet")
With Us
.Range("A:AJ").Select
Selection.Copy
End With
U.Close SaveChanges = True
With DestinationWorkbook
.Sheets("sheet").Range("A:AJ").PasteSpecial Paste:=xlPasteAll
.Save
End With
Just to help in case you didn't find the answer till now :
In my case this message came out when I redimensioned the application window while it was maximized :
e.g. Application.width = 100 (on Excel 2003 or 2007)
The solution in this case, is to first bring the application window to NORMAL.
e.g. ActiveWindow.WindowState = xlNormal