VBA PowerPoint Run-time error '-2147467259' (80004005): Presentation.Close: Failed

46 views Asked by At

I have a macro which is running from Excel. This macro opens PowerPoint slides, performs some work, and then closes them. The problem I am having is the following:

error

This error message appears seemingly randomly throughout the course of the macro's runtime. This error is not guardable with On Error GoTo Label and it seems that it is time dependent (based on some race condition), as at a later stage, again seemingly randomly, the line will run without issue.

The specific code which causes this error is as follows:

myPresentation.Close
1

There are 1 answers

0
Sancarn On BEST ANSWER

Things I tested:

myPresentation.saved=true
myPresentation.Close

Which didn't fix the issue

myPresentation.saved=true
myPresentation.windows(1).activate
myPresentation.Close

Also didn't work. In the end the most stable solution I have come across is the following:

'This function is implemented as a fix for an issue where VBA reports "Presentation.Close: Failed"
'@param pres as Object<PowerPoint.Presentation> - The presentation to close.
'@docs https://stackoverflow.com/questions/78156015/vba-powerpoint-run-time-error-2147467259-80004005-presentation-close-fail/78156016#78156016
Public Sub ClosePresentation(ByVal pres As Object)
  pres.windows(1).Activate
  While Not pres.Saved
    pres.Saved = True
  Wend
  stdWindow.CreateFromApplication(pres.Application).Quit
End Sub

This utilises the library stdWindow - which is an open source library I maintain. Ultimately this sense the close message to the window indirectly (via the Windows API) which seems to be more stable, as I suppose this is exactly how users usually close windows.

It is important to note that setting saved appears to have some race condition, hence the loop.