Excel VBA CreateObject("Outlook.Application") causes OLE Error as Outlook 2019 didn't exit properly

61 Views Asked by At

My Excel VBA program, running on Windows 10 64 bit, sends an email via Outlook. This usually works fine but every so often it hangs with a popup stating "Microsoft Excel is waiting for another application to complete an OLE action".

This is caused by the following lines:

Dim appOutlook, mItem as Object
On Error Resume Next
Set appOutlook = CreateObject("Outlook.Application")
Set mItem = appOutlook.CreateItem(0)
' set mItem.To,.Subject,.body fields
mItem.send
Set mItem = Nothing
Set appOutlook = Nothing

It seems that Outlook 2019 is not exiting properly (via Alt-F4) and gets stuck in Task Manager. I have no idea why, and I've tried removing Add-Ins. Until I End Task, Outlook won't load and the Excel VBA will generate the OLE error on executing the CreateObject() line, where it hangs until the popup is cleared.

Any idea how to fix this? Ideally VBA shouldn't hang on an error anyway, and of course Outlook shouldn't get stuck on exiting. So two problems really. Most important thing is stop the VBA getting stuck, even if it means the email isn't sent.

1

There are 1 best solutions below

4
Dmitry Streblechenko On

Modern versions of Outlook exit even if there are still outstanding references to its COM objects - the older versions used to hang until all references were released. The only exceptions now are the Inspector and Explorer objects: even if they are not visible, holding a reference to them woudl prevent Outlook and exiting. If Outlook hangs after your code touches it, make sure you don't store Inspector and Explorer objects in global variables.