Error Closing OLEObject Excel.Sheet After Creation - vba

Say you wish to create and then close a linked excel sheet:
Dim shp As shape
Set shp = Application.ActiveDocument.Shapes.AddOLEObject(ClassType:="Excel.Sheet")
DoEvents
shp.OLEFormat.Object.Close
This fails with this error:
Run time error '1004'
Close method of Workbook class failed
Why? I can't seem to find any examples of this occurring in word, the closest example I can find is this, which is more related with the user form than the actual function.
The error seems very generic, is there any way to get a more specific reason "why" the close method is failing? It seems if you google around, you'll find this error is thrown for all sorts of reasons(example, another example) but non of these seem to have anything to add to this particular issue.
Note: A similar error occurs with "shp.OLEFormat.Object.Save"

The usual reason for this question is to get the object to "unselect" on the document surface...
In my experience, it's not possible to close a workbook activated on the document surface. This has to do with how OLE Embedding works. Application.Quit should work, but doesn't (in my experience) with Excel.
The most reliable way to achieve this has been to force the workbook to open in an independent Excel.Application window, then you can close and save the workbook and Quit the Excel application.
Something like the following should work:
Dim shp as Word.Shape
Dim oleF as Word.OLEFormat
Dim xlBook as Excel.Workbook 'or Object
Dim xlApp as Excel.Application 'or Object
Set shp = Application.ActiveDocument.Shapes.AddOLEObject(ClassType:="Excel.Sheet")
Set olef = shp.OLEFormat
oelf.DoVerb VerbIndex:=wdOLEVerbOpen
Set xlBook = olef.Object
Set xlApp = xlBook.Application
'Do things here
xlBook.Close
xlApp.Quit
Set xlApp = Nothing
Set xlBook = Nothing
Note that for debugging purposes you might want to set xlApp.Visible = True.
It can happen that xlBook.Close still generates an error, even though the behavior other than that is correct. In that case the error can be surpressed by turning off error messages for this one line, re-instating it following:
On Error Resume Next
xlBook.Close
On Error GoTo 0

Here's what I came up with:
Set xlBook = olef.Object
Set xlApp = xlBook.Application
xlApp.SendKeys "{ESC}"
This will stop the Excel.Application and return the user to Word. Same thing as running the commanding to close the Workbook.

Related

Access 2007 VBA - Open Two Excel Workbooks

I am using Access 2007. In my Access file I have VBA code that opens an Excel
workbook when the Access program begins. The Excel workbook remains open
while the program is running. I use this code to open the workbook:
Public xl As Object
Public wb1 As Object
Set xl = New Excel.Application
Set wb1 = xl.Workbooks.Open("c:\Book1.xlsx")
Now while the program is running I may need to open a second Excel workbook,
get some data from it, then close it. I used this code:
Public wb2 As Object
Set wb2 = xl.Workbooks.Open("c:\Book2.xlsx")
But this doesn't work. It seems that the first workbook may have closed because
if I do debug.print Workbooks.Count the response is "0".
Any suggestions on how to open a second workbook and still have the first workbook open?
Should I create a second instance of Excel and use that to open the second workbook?
Thank you.
You may have more luck with this procedure instead:
Sub OpenExcel(fName As String)
Dim xlApp As Object
On Error Resume Next
Set xlApp = GetObject(, "Excel.Application")
If Err.Number <> 0 Then
'Excel wasn't running, start it from code
Set xlApp = CreateObject("Excel.Application")
End If
On Error GoTo 0
xlApp.Workbooks.Open (fName)
End Sub
With your code it's possible that Excel was opening but the second workbook did not default to visible, which could be set with xl.Visible = True. Alternatively, a second xl object could have helped.
Regardless, this method is safer is a number of ways.
Make sure when you're done, make sure you clean up (and free up memory) with something like xlApp.Quit and Set xlApp = Nothing.
In fact, I'd suggest you reboot right now... before you do, take a look at the running processes in your Task Manager - I wouldn't be surprised if you have several "invisible" instances of Excel running. :)

Powerpoint VBA dont close Excel

My VBA code in Powerpoint wont "kill" my excel application.
it still runs if i have a look in task manager.
I would like to close it the right way rather than kill.
Anyone that could help me? I already searched and tried to get it working but with no luck.
Public Sub OnSlideShowPageChange(ByVal Wn As SlideShowWindow)
If Wn.View.CurrentShowPosition = 2 Then
Dim xlApp As Object
Dim xlWorkBook As Object
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = False
Set xlWorkBook = xlApp.Workbooks.Open("D:\ELE_powerpoint\book1.xlsx", True, False)
With xlWorkBook.ActiveSheet
txt1 = xlWorkBook.sheets(1).Range("A2")
txt2 = xlWorkBook.sheets(1).Range("A3")
txt3 = xlWorkBook.sheets(1).Range("A4")
End With
ActivePresentation.Slides(2).Shapes("a2").TextFrame.TextRange = txt1
ActivePresentation.Slides(2).Shapes("a3").TextFrame.TextRange = txt2
ActivePresentation.Slides(2).Shapes("a4").TextFrame.TextRange = txt3
Set xlApp = Nothing
Set xlWorkBook = Nothing
End If
End Sub
Try xlApp.Quit before Set xlApp = Nothing
Set xlApp = Nothing
That instruction sets the xlApp object reference to Nothing. It doesn't destroy the object it's referring to, but it prevents further code from using that reference.
Excel is a rather complex application; creating an instance of an Excel.Application object has many implications, and in order to properly shut itself down, it needs to run through a certain sequence of instructions (unload Excel and COM add-ins, close any opened file, tear down the VBE if it was initialized - which in turn may need to tear down its own add-ins, etc.) - by setting your reference to Nothing, you say "I don't need it anymore" - but what of the COM add-ins that still use it? That workbook that's still open is a Workbook object with an Application property that also references the very same object you were referring to - and these references aren't gone yet!
As Tim and Tom said, you need to call the Quit method of the Excel.Application instance, so that it can clean itself up.
And if that's the last thing your code does, then you probably don't even need to Set xlApp = Nothing, since the VBA runtime will know that it doesn't need to hold on to the xlApp reference after it's out of scope; Set xlWorkbook = Nothing is superfluous as well.
Quitting Excel will close the unmodified workbook you've opened, but since you opened it, I'd argue that it's good form to close it yourself - just call xlWorkbook.Close before you call xlApp.Quit.

SLOW in changing SourceFullName in powerpoint linked objects through vba

I'm experiencing SLOW changing, NOT updating, the links in powerpoint presentation for linked objects.
Sample codes are as below:
For Each sld In ActivePresentation.Slides
For Each shp In sld.Shapes
If shp.Type = msoLinkedOLEObject Then
Src_Old = Split(shp.LinkFormat.SourceFullName, "!")(0)
Src_New = Src_Path & "\" & Src_Book_Name
shp.LinkFormat.SourceFullName = Replace(shp.LinkFormat.SourceFullName, Src_Old, Src_New)
End If
Next shp
Next sld
During each iteration, the external source file will be reopen and the link will be updated, which significantly slow down the running. So the questions are:
Is there anyway to force NOT updating the link but just change the texts for SourceFullName?
Even if the answer is NO, is there anyway to stop reopening the external source files each iteration?
Thanks in advance.
I experienced the same problem. This single command line was taking up to 16 seconds to execute. Changing the update method to manual improved to 11 seconds. What really solved was opening the reference file in backgound, without even showing to user, in read only node. Down to 0.6 seconds. Also valid to the update method.
Dim xlApp As Object
Dim xlWorkBook As Object
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = False
xlApp.DisplayAlerts = False
Set xlWorkBook = xlApp.Workbooks.Open(strDBPath, False, True)
When you finish dont forget to clean up the mess.
xlWorkBook.Close
Set xlWorkBook = Nothing
xlApp.Quit
Set xlApp = Nothing
Can you try switching to manual update mode by using this before changing the SourceFullName property:
shp.LinkFormat.AutoUpdate = ppUpdateOptionManual
And then using the Update method to manually refresh the content when needed:
shp.LinkFormat.Update
You might also be able to use the BreakLink method but I'm not sure if this is what you want:
shp.LinkFormat.BreakLink

VBA: Reading excel data into word

I am making a simple form that extract the data from my excel sheet, such as name, date of birth, and address. And inserting them into my word form, I am doing 20-30 sheets everytime, so I think it might be able to save the copying & pasting time.
I tried to follow this tutorial: http://www.makeuseof.com/tag/integrate-excel-data-word-document/
And created a button with a simple label named m_name, for member's name. But it tells me Compile error: User-defined type not defined. And flaged on line 1.
I am using Word 2003, (I am not able to find the Tools > Reference as the guide was asking for). I am not sure if it is related to this error.
Private Sub CommandButton1_Click()
Dim objExcel As Excel.Application
Dim exWb As Excel.Workbook
Set exWb = objExcel.Workbooks.Open("U:\test.xls")
ThisDocument.m_name.Caption = exWb.Sheets("Member's Data").Cells(3, 3)
exWb.Close
Set exWb = Nothing
End Sub
Yes, it's very important to set references according to the tutorial.
However, change these two lines:
Dim objExcel As Excel.Application
Dim exWb As Excel.Workbook
to:
Dim objExcel As Object
Set objExcel = CreateObject("Excel.Application")
and the code should work, too.

Open Excel file in VBA from Powerpoint

I'm trying to open the Excel file using VBA in Powerpoint 2010 with the help of following code.
Private Sub CommandButton1_Click()
Dim xlApp As Excel.Application
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
xlApp.Workbooks.Open "C:\lol\Book1.xlsx", True, False
Set xlApp = Nothing
Range("A8").Value = "Hello"
End
But I'm getting the following error.
Compile Error
User Defined type not defined.
Am I missing something. Can anyone share the sample piece of code to open an excel file, change a cell value and close Excel file in Powerpoint 2007 and 2010 using VBA.
I have searched a lot and tried different pieces of code, but getting the same error everytime. :(
Thanks in advance. :)
Have you added a reference to the Excel Object Model? That would save you having to use the late bound objects (and you get the benefit of having the Intellisense help when you are coding).
You need to go to Tools -> References and check the "Microsoft Excel v.x Object Library" (I think that number changes depending on the version of office you are using.
Your code should work if you do that, you should also remove the
CreateObject("Excel.Application")
line and replace it with
Set xlApp = new Excel.Application
And move the
Set xlApp = nothing
line to the end of your subroutine.
The rest of your code looks fine to me.
Late binding code would be this
Private Sub test()
Dim xlApp As Object
Dim xlWorkBook As Object
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
Set xlWorkbook = xlApp.Workbooks.Open("C:\lol\Book1.xlsx", True, False)
xlWorkbook.sheets(1).Range("A8").Value = "Hello"
Set xlApp = Nothing
Set xlWorkbook = Nothing
End Sub
It's better to use early binding though.