I've been asked to troubleshoot a VBA script that sends an email from an Access database. The DB and VBA was developed on Access 2010 (Data stored in a SQL db), and likely targets Outlook 2010.
Currently, we use Outlook 2013 and 2016.
When my script (noted below) runs, an error is generated on the Outlook.Application declaration: User Defined Data Type Not Defined.
Here's be beginning of the script, where we define data types.
Option Compare Database
Option Explicit
' InitOutlook sets up outlookApp and outlookNamespace.
Private outlookApp As Outlook.Application
Private outlookNamespace As Outlook.NameSpace
The rest of the script is below. It is being triggered by a form button directly calling SendEmail() and passing an email address as a variable.
Private Sub InitOutlook()
' Initialize a session in Outlook
Set outlookApp = New Outlook.Application
'Return a reference to the MAPI layer
Set outlookNamespace = outlookApp.GetNamespace("MAPI")
'Let the user logon to Outlook with the
'Outlook Profile dialog box
'and then create a new session
outlookNamespace.Logon , , True, False
End Sub
Public Sub SendEmail(varTo As Variant)
Dim mailItem As Outlook.mailItem
InitOutlook
Set mailItem = outlookApp.CreateItem(olMailItem)
mailItem.To = varTo & ""
mailItem.Subject = "subject text"
mailItem.Body = "Body text"
mailItem.Display
Set mailItem = Nothing
CleanUp
End Sub
I'm not super familiar with VBA / Access, but I've worked with VB.NET and I've been fairly certain since the beginning that this was a simple matter of "it's missing an imports statement or a reference."
After digging into it a bit, I've found online here that in order to use this functionality, you must add a reference to the Microsoft Outlook XX.X Object Library.
I haven't seen the references that are on this database yet (Working on getting there now), as I have limited access to this access DB, as it contains a lot of sensitive information and I have to be supervised when viewing it.
However, given that we used Outlook 2010 when we wrote this script, and are now split between Outlook 2013 and 2016, I believe we need to update this reference to a more recent one.
I was discussing this with a coworker here, and he asked me an important question:
Can we reference more than one version of the Microsoft Outlook Object Library?
If we target the most recent version of the library, for say, Outlook 2016, will the script not function for Outlook 2013 users?
Update: I found out through testing that if we used the MS Outlook 16.0 object library, Outlook 2013 would not recognize the reference, and would throw errors that the reference was missing.
If we used the MS Outlook 15.0 library, the script worked on machines with either version of outlook.