How to Create an Outlook VBA Macro

Unlike Word and Excel, as we have seen, to create our Outlook VBA Macro we won't have the help of a Macro Recorder.

Before we get started, make sure the Macro Security setting is not set to High. If it is, your macros simply won't run. Low is not recommended. Set the Option to Medium.

In Outlook, go to Tools>Macro>Security... 

Outlook VBA Macro


Click on the Medium Option.

Copy the following code...

Sub SendMail()

On Error GoTo On_Error

Dim nsSession As Outlook.NameSpace
Dim fldFolder As Outlook.MAPIFolder
Dim itmMail As Outlook.MailItem
Dim MailRecipient As Outlook.Recipient
Dim inputTemp As Outlook.Recipient

Set nsSession = Application.Session
If Not nsSession Is Nothing Then
nsSession.Logon , , False, False
Set fldFolder = nsSession.GetDefaultFolder(olFolderOutbox)
If Not fldFolder Is Nothing Then
Set itmMail = fldFolder.Items.Add(olMailItem)
If Not itmMail Is Nothing Then
tmpInput = InputBox("Enter the email Address")
Set oRecipient = itmMail.Recipients.Add(tmpInput)
oRecipient.Type = olTo
Set oRecipient = Nothing
tmpInput = InputBox("Enter the email Subject")
itmMail.Subject = tmpInput
tmpInput = InputBox("Enter the email Message")
itmMail.Body = tmpInput
itmMail.Send
Set itmMail = Nothing
End If

Set fldFolder = Nothing

End If
nsSession.Logoff

End If
Exiting:
Set nsSession = Nothing
Exit Sub
On_Error:
MsgBox "err=" & Err.Number & " " & Err.Description
Resume Exiting
End Sub
Open the VBA Editor in Outlook, ALT+F11. In the Project pane at the upper left, open the hierarchy and double click on ThisOutlookSession...

Now, paste the Outlook VBA macro code in the code pane at the right.

This site is powered by Site Build It!. If you enjoy it, please check out the
Site Build It homepage
 to learn more and on how to build a success-guaranteed site with no technical skills.

Custom Search






Return from an Outlook VBA Macro to VBA Code Samples

Return to our Home Page