Runtime error 287. Sending Emails through Outlook using VBA in Access

LiamH picture LiamH · Mar 31, 2016 · Viewed 15.8k times · Source

I have a case where one user would like to receive notifications of when deliveries are added to an Access Database. The simplest method I could think of was to set up an automated email via Outlook 2010. The following code is what I have in place:

Dim oApp As Outlook.Application
Dim oMail As MailItem
Dim varDnoteRef2 As String
Dim varuser As String
varuser = DLookup("[Employee_Name]", "employees", "[Employee_ID]=" & TempVars!gloggedin)
varDnoteRef2 = DLast("Supplier_Dnote_Ref", "Supplier_Dnotes")

Set oApp = CreateObject("Outlook.application")
Set oMail = oApp.CreateItem(olMailItem)
oMail.Body = "A Delivery Note has been added to the Database by " & varuser & " on " & Now() & "." & _
             vbNewLine & "Delivery Note: " & varDnoteRef2
oMail.Subject = "Automatic Notification: Delivery Note"
oMail.To = "[email protected]"
oMail.Send
Set oMail = Nothing
Set oApp = Nothing

This code works perfectly when the person who activates the code has Outlook open. However, when the user doesn't have Outlook launched the user gets an error at the oMail.send line.

error # 287 error line 0 application-defined or object-defined error.

What they get is a small icon on the desktop that is the outlook symbol with a gear/cog and message saying another program or application is using outlook. Which is what I expect. But why does it fail on the send?

How can I get around this error/ is there a solution?

Edit (Update)

What is more strange is that when I step through my code using F8. IT WORKS!! But still not when I call the code from a form action e.g. button_on_click

Answer

LiamH picture LiamH · Apr 1, 2016

Well this is something I have never come across before, however, I have found a solution.

The error message itself got me wondering why the send command wasn't recognising the defined application. I questioned whether the code was running too fast. (I don't know where this light bulb moment came from but it has fixed the issue).

I have simply inserted a loop to force a delay before the send operation. I did this because Access doesn't recognise application.wait.

Testing so far seems successful!

Dim T1 As Variant
Dim T2 As Variant

T1 = Now()
T2 = DateAdd("s", 1, T1)

Do Until T2 <= T1
    T1 = Now()
Loop
oMail.Send

This procedure will not be run very often, maybe 5 times in a day max. So I am not worried about the one second delay causing any real-time issues.