Option Explicit
'Early Binding
'Declare our app object by adding a reference to
'MS Outlook xx.0 Object Library
Private moApp As Outlook.Application
Private Sub Command1_Click()
'Declare our Early Bound objects
Dim oMail As Outlook.MailItem
'Create a new email item passing our constant to identify a MailItem type object
Set oMail = moApp.CreateItem(olMailItem)
'Set the new items properties.
With oMail
.BodyFormat = olFormatPlain
.Body = "Blah, blah, blah."
.Recipients.Add "vbofficeguru@example.com"
.Recipients.ResolveAll
.Subject = "Early Bound Automation Example"
.To = "you@example.com"
.Save
.Send 'Send our Spam, err I mean email lol.
End With
Set oMail = Nothing
End Sub
Private Sub Form_Load()
'Error trap in case Office is not installed
On Error GoTo MyError
'Create a new instance of Outlook or attach to an already running instance of Outlook.
'Use only one method or the last one initialized will win out.
'Create a new instance of Outlook.
Set moApp = CreateObject("Outlook.Application")
'Or another method specific to Early Binding...
Set moApp = New Outlook.Application
'Attach to an already running instance of Outlook.
Set moApp = GetObject(, "Outlook.Application")
Exit Sub
MyError:
If Err.Number = 429 Then
MsgBox "The desired Office application is not installed or can not be created.", vbOkOnly+vbExclamation
Else
MsgBox Err.Number & " - " & Err.Description, vbOkOnly+vbExclamation
End If
End Sub
Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
'If we created a new application object then lets quit it and clean up
moApp.Quit
Set moApp = Nothing
'If we attached to an already running instance, if we want we can leave it running but still clean up
Set moApp = Nothing
End Sub