Follow by Email

Tuesday, March 18, 2014

Basic examples for Outlook VBA

This post contains few basic examples for VBA in Microsoft Outlook. To get developer tab visible, File -> Option -> Customize Ribbon -> Developer.

Let see a simple example to send an email. Below is the basic code which will generate and shoot the email. In visual Basic Editor, use ThisOutlookSession or any other user modules.

Private Sub SendEmail()
Dim olObj, mlObj
Set olObj = CreateObject("Outlook.Application") 'declaring object
Set mlObj = olObj.CreateItem(0) 'declaring an email item
With mlObj
.To = "" 'Give your email
.Subject = "Testmail" ' Give the subject
.Body = "Testmail" ' Give the Body
.Send 'command to send the email
End With
Set olObj = Nothing 'Clear the memory
Set mlObj = Nothing
End Sub

If you are asked for permission while before sending the email, then you can set the security level accordingly to avoid dialogboxes. Here is an another example for reading a subject from opened email item

Dim oMail As Outlook.MailItem 'declare item variable
Dim sSub As String
Set oInspector = Application.ActiveInspector 'declare an object
If oInspector Is Nothing Then ' This is to skip if no email is opened
MsgBox "No Mail is opened"
Exit Sub
End If
Set oMail = Application.ActiveInspector.CurrentItem 'assign the current email item
sSub = oMail.Subject 'Assign subject
sBob = oMail.Body ‘This will read Body
msgBox (sSub)

Using Regex pattern you can get any information from subject line and then process it accordingly. similarly, you can also forward the email item to any. But Outlook 'Rule' feature allows you to set directly forward, However below code is for your customization

Sub email_forward()
Set myitem = ActiveExplorer.Selection(1).Forward
myitem.Subject = Replace(myitem.Subject, "FW:", "")
myitem.To = ""
End Sub


Post a Comment

You Can use HTML code once it converted to NCcode by NCode converter