Vba excel and outlook

We have seen VBA in Excel and how we automate our tasks in Excel by creating macros. In Microsoft Outlook, we also have a reference for VBA and can control Outlook using VBA. It makes our repeated tasks in Outlook easier to automate. Like Excel, we need to enable the Developer feature to use VBA in Outlook.

The beauty of VBA is we can reference other Microsoft objects like PowerPoint, Word, and Outlook. We can create beautiful presentations. We can work with Microsoft word documents. Finally, we can send the emails as well. Yes, you heard it right. We can send emails from Excel. It sounds awkward but, at the same time, puts a smile on our faces as well. This article will show you how to work with Microsoft Outlook objects from excel using VBA codingVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more. Read on.

Table of contents
  • VBA Outlook
    • How do we Reference Outlook from Excel?
    • Write a Code to Send Emails from VBA Outlook from Excel
    • Recommended Articles

VBA Outlook

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA Outlook (wallstreetmojo.com)

How do we Reference Outlook from Excel?

Remember, Outlook is an object. Therefore, we need to set the reference to this in the object reference library. To set the Outlook object to reference, follow the below steps.

Step 1: Go to Visual Basic Editor.

Step 2: Go to Tools > Reference.

Reference Outlook 1

Step 3: In the below references, object library, scroll down, and select “MICROSOFT OUTLOOK 14.0 OBJECT LIBRARY.”

Check the “MICROSOFT OUTLOOK 14.0 OBJECT LIBRARY” box to make it available for Excel VBA.

Reference Outlook 1-1

Now, we can access the VBA Outlook object from Excel.

Write a Code to Send Emails from VBA Outlook from Excel

We can send the emails from excel through the outlook app. For this, we need to write VBA codes. Then, follow the below steps to send the emails from Outlook.

You can download this VBA Outlook to Excel Template here – VBA Outlook to Excel Template

Step 1: Create a sub procedure.

Code:

Option ExplicitVBA option explicitly makes a user mandatory to declare all the variables before using them; any undefined variable will throw an error while coding execution. We can enable it for all codes from options to require variable declaration.read more

Sub Send_Exails()

End Sub

VBA Outlook Step 1

Step 2: Define the variable as VBA Outlook.Application.

Code:

Option Explicit

Sub Send_Exails()

  Dim OutlookApp As Outlook.Application

End Sub

VBA Outlook Step 2

Step 3: The above variable reference the VBA Outlook application. In Outlook, we need to send emails, so define another variable as Outlook.MailItem.

Code:

Option Explicit

Sub Send_Exails()

  Dim OutlookApp As Outlook.Application
  Dim OutlookMail As Outlook.MailItem

End Sub

VBA Outlook Step 3

Step 4: Now, both variables are object variables. We need to set them. First, set the variable “OutlookApp” as New Outlook.Application.

Code:

Sub Send_Exails()

  Dim OutlookApp As Outlook.Application
  Dim OutlookMail As Outlook.MailItem

  Set OutlookApp = New Outlook.Application

End Sub

VBA Outlook Step 4

Step 5: Now, set the second variable, “OutlookMail,” as below.

Set OutlookMail=OutlookApp.CreateItem(olMailItem)

Code:

Sub Send_Exails()

  Dim OutlookApp As Outlook.Application
  Dim OutlookMail As Outlook.MailItem

  Set OutlookApp = New Outlook.Application
  Set OutlookMail = OutlookApp.CreateItem(olMailItem)

End Sub

VBA Outlook Step 5

Step 6: Now, using With statement access VBA Outlook Mail.

Code:

Sub Send_Exails()

  Dim OutlookApp As Outlook.Application
  Dim OutlookMail As Outlook.MailItem

  Set OutlookApp = New Outlook.Application
  Set OutlookMail = OutlookApp.CreateItem(olMailItem)

  With OutlookMail

  End With

End Sub

VBA Outlook Step 6

Now, we can access all the items available with email items like “Body of the email,” “To,” “CC,” “BCC,” “Subject,” and many more things.

Step 7: Inside the statement, we can see the IntelliSense list by putting a dot.

VBA Outlook Step 7

Step 8: First, select the body format as olFormatHtml.

Code:

With OutlookMail
    .BodyFormat = olFormatHTML

End With

VBA Outlook Step 8

Step 9: Now display the email.

Code:

With OutlookMail
  .BodyFormat = olFormatHTML
  .Display
End With

VBA Outlook Step 9

Step 10: We need to write the email in the body of the email. For this, select HtmlBody.

Code:

With OutlookMail
  .BodyFormat = olFormatHTML
  .Display
  .HTMLBody = "Write your email here"
End With

VBA Outlook Step 10

Below is the example of the body of the email writing.

Step 11

Step 11: We need to mention the receiver’s email ID after writing the email. For this access, “To.

Step 12

Step 12: Next, mention for whom you want to CC the email.

Step 13

Step 13: Now, mention the BCC email ids,

Step 14

Step 14: Next, we need to mention the subject of the email we are sending.

Step 15

Step 15: Now, add attachments. If you want to send the current workbook as an attachment, then use the attachment as This workbook.

Step 16

Step 16: Finally, send the email by using the Send method.

Step 17

Now, this code will send the email from your VBA outlook mail. Use the below VBA code to send emailsWe can use VBA to automate our mailing feature in Excel to send emails to multiple users at once. To use Outlook features, we must first enable outlook scripting in VBA, and then use the application method.read more from your outlook.

To use the below code, you must set the object reference to “MICROSOFT OUTLOOK 14.0 OBJECT LIBRARY” under the object library of Excel VBA.

The library is called early binding by setting the reference to the object. We need to set the reference to the object library because without setting the object library as “MICROSOFT OUTLOOK 14.0 OBJECT LIBRARY. We cannot access the IntelliSense list of VBA properties and methods. It makes writing code difficult because you need to be sure of what you are writing in terms of technique and spelling.

Sub Send_Emails()
'This code is early binding i.e in Tools > 
Reference >You have check "MICROSOFT OUTLOOK 14.0 OBJECT LIBRARY"

  Dim OutlookApp As Outlook.Application
  Dim OutlookMail As Outlook.MailItem

  Set OutlookApp = New Outlook.Application
  Set OutlookMail = OutlookApp.CreateItem(olMailItem)
  
  With OutlookMail
    .BodyFormat = olFormatHTML
    .Display
    .HTMLBody = "Dear ABC" & "<br>" & "<br>" & "Please find the attached file" & 
    .HTMLBody
    'last .HTMLBody includes signature from the outlook.
''<br> includes line breaksLine break in excel means inserting a new line in any cell value. To insert a line break, press ALT + Enter. As we insert a line break, the cell's height also increases as it represents the data.read more b/w two lines
    .To = "[email protected]"
    .CC = "[email protected]"
    .BCC = "[email protected];[email protected]"
    .Subject = "Test mail"
    .Attachments = ThisWorkbook
    .Send
  End With

End Sub

Recommended Articles

This article has been a guide to VBA Outlook. Here, we learn how to send emails from Outlook using VBA codes, examples, and a downloadable template. Below are some useful Excel articles related to VBA: –

  • Excel VBA ThisWorkbook
  • VBA ArrayList
  • VBA For Next Loop
  • List of String Functions in VBA
  • VBA Write Text File

VBA Outlook

Excel VBA Outlook Function

We work on lots & lots of Excel files on a daily basis and we send to many users on a daily basis. We write the same Message in the email daily and send that excel file. This gives us the scope of the automation of this task. You heard it right. This task of writing an email and sending the file can be automated with the help of VBA. The reason is that VBA can use a reference with different Microsoft Objects like outlook, word, PowerPoint, paint, etc.

So we can send the email with the help of VBA. Now I am sure you all will be excited to know how we can send an email with the help of VBA.

We will learn in this article on how to use the Outlook as Microsoft object from excel using VBA coding and how we can send an email including an attachment with the help of VBA.

How to Use Excel VBA Outlook Function?

To use VBA Outlook function, we need to do two things.

You can download this VBA Outlook Excel Template here – VBA Outlook Excel Template

  1. Reference Microsoft Outlook Object from Object Library in VBA.
  2. Write VBA code to send emails in the VBA module.

#1 – Reference of Outlook from Excel

As you know Outlook is an object and we need to provide a reference to Outlook object. So there is an Object reference library in VBA which we need to use for reference.

Follow the below steps to use the Object Reference Library.

Step 1: In the Developer Tab click on Visual Basic to open the VB Editor.

VBA Outlook Example 1-1

Step 2: Go to Tools and then select References as shown in the below screenshot.

VBA Outlook Example 1-2

Step 3: Scroll down in the Reference Object library and select “Microsoft Outlook 16.0 Object Library” to make it available for Excel VBA.

VBA Outlook Example 1-3

Depending on the Microsoft office, the Outlook version may be different. In our case, it is 16.0. You can use “Microsoft Outlook 14.0 Object Library if that is the version shown in your computer.

Check the box of Microsoft Outlook as shown in the above screenshot. Now we can use the Microsoft Outlook object in Excel VBA.

This process of setting the reference to “MICROSOFT OUTLOOK 16.0 OBJECT LIBRARY” is known as Early Binding. Without setting the object library as “MICROSOFT OUTLOOK 16.0 OBJECT LIBRARY” we cannot use the IntelliSense properties and methods of VBA which makes writing the code difficult.

#2 – Write a Code to Send Emails from VBA Outlook from Excel

Follow the below steps to write the VBA code to send email from outlook from Excel.

Step 1: Create a Sub Procedure by naming the macro. We will name macro as “send_email” as shown in the below screenshot.

Code:

Option Explicit

Sub Send_email()

End Sub

VBA Outlook Example 1-4

Step 2: Define the variable as Outlook. Application as shown in the below screenshot. This is the reference to the VBA Outlook Application.

Code:

Option Explicit

Sub Send_email()

Dim OutlookApp As Outlook.Application

End Sub

VBA Outlook Example 1-5

Step 3: We need to send an email in Outlook so define another variable as “Outlook.Mailitem” as shown in the below screenshot.

Code:

Option Explicit

Sub Send_email()

Dim OutlookApp As Outlook.Application
Dim OutlookMail As Outlook.MailItem

End Sub

VBA Outlook Example 1-6

Step 4: In the previous steps we have defined the variable now we need to set them.

Now set the first variable “Outlook Application” as “New Outlook.Application” as shown in the below screenshot.

Code:

Option Explicit

Sub Send_email()

Dim OutlookApp As Outlook.Application
Dim OutlookMail As Outlook.MailItem
Set OutlookApp = New Outlook.Application

End Sub

VBA Outlook Example 1-7

Step 5: Now set the Second Variable “Outlook Mail” with the below code.

Code:

Option Explicit

Sub Send_email()

Dim OutlookApp As Outlook.Application
Dim OutlookMail As Outlook.MailItem
Set OutlookApp = New Outlook.Application
Set OutlookMail = OutlookApp.CreateItem(olMailItem)

End Sub

VBA Outlook Example 1-8

Step 6: We can now use the VBA Outlook using the “With” statement as shown in the below screenshot.

Code:

Option Explicit

Sub Send_email()

Dim OutlookApp As Outlook.Application
Dim OutlookMail As Outlook.MailItem
Set OutlookApp = New Outlook.Application
Set OutlookMail = OutlookApp.CreateItem(olMailItem)
With OutlookMail

End Sub

VBA Outlook Example 1-9

We now have all the access to Email items like “To”, “CC”, “BCC”, “subject”, ” Body of the email” and Many more items.

Step 7: Inside the “With” statement, we can see a list by putting a dot which is known as “Intellisense List”.

VBA Outlook Example 1-10

Step 8: First select the body format as olFormatHtml as shown in the below screenshot.

Code:

With OutlookMail
  .BodyFormat = olFormatHTML

End Sub

Select body format

Step 9: Select “.Display” to display the mail as shown in the below screenshot.

Code:

With OutlookMail
  .BodyFormat = olFormatHTML
  .Display

End Sub

Select Display

Step 10: Select “.HTMLbody” to write the email as shown in the below screenshot.

Code:

With OutlookMail
  .BodyFormat = olFormatHTML
  .Display
  .HTMLBody = "write your email here"

End Sub

VBA Outlook Example 1-13

We need to remember a few things while writing the email in VBA code.

“<br>” is used to include line breakup between two lines. To add signature in the email, you need to enter “& .HTMLbody”

See below example on how to write the mail in VBA.

Code:

With OutlookMail
  .BodyFormat = olFormatHTML
  .Display
  .HTMLBody = "Dear ABC" & "<br>" & "Please find the attached file" & .HTMLBody

End Sub

VBA Outlook Example 1-14

Step 11: Now we need to add the receiver of the email. For this, you need to use “.To”.

Code:

.To = "[email protected]"

Add receiver of the Email

Step 12: If you want to add someone in “CC” & “BCC”, you can use “.CC” and “.BCC” as shown in the below screenshot.

Code:

.CC = "[email protected]"
.BCC = "[email protected]"

VBA Outlook Example 1-16

Step 13: To add a subject for the email that we are sending, we can use “.Subject” as shown in the below screenshot.

Code:

.Subject = "TEST MAIL"

Add a Subject for the Email

Step 14: We can add our current workbook as an attachment in the email with the help of “.Attachment” Property. To do that first declare a variable Source as a string.

Code:

Dim source_file As String

VBA Outlook Example 1-18

Then use the following code to attach the file in the email.

Code:

source_file = ThisWorkbook.FullName
.Attachments.Add source_file

Attach file in the Email

Here ThisWorkbook is used for the current workbook and .FullName is used to get the full name of the worksheet.

Step 15: Now the last code is to finally send the email for which we can use “.send”. But make sure to close the With and Sub procedure by “End with” and “End Sub” as shown in the below screenshot.

Last Code for Email

So the code is finally ready to send an email. We need to just run the macro now.

Step 16: Run the code by hitting F5 or Run button and see the output.

Sending an Email

Final Full code

So below is the final code on how to send an email with the help of VBA Outlook.

Code:

Option Explicit

Sub Send_email()

Dim OutlookApp As Outlook.Application
Dim OutlookMail As Outlook.MailItem
Dim source_file As String
Set OutlookApp = New Outlook.Application
Set OutlookMail = OutlookApp.CreateItem(olMailItem)
With OutlookMail
  .BodyFormat = olFormatHTML
  .Display
  .HTMLBody = "Dear ABC" & "<br>" & "Please find the attached file" & .HTMLBody

  .To = "[email protected]"
  .CC = "[email protected]"
  .BCC = "[email protected]"
  .Subject = "TEST MAIL"

  source_file = ThisWorkbook.FullName
  .Attachments.Add source_file
  .Send

End With
End Sub

Example of VBA Outlook Function

Suppose there is a Team Leader and he wants to send a daily email for follow up of each member’s activity. The email will be like this.

Hi Team,

Request you to kindly share your actions on each of your follow up items by 11 AM today.

Thanks & Regards,

Unknown

Follow the steps mentioned above for referencing the Microsoft Object and writing the VBA coding or you can just modify the code accordingly.

So with all the code remaining same, we need to change few things in the code be like Email ID of the receiver, Subject, Body of the email and there will be no attachment in the email.

Below is the modified code we are using to write this email.

Code:

Sub Send_teamemail()

Dim OutlookApp As Outlook.Application
Dim OutlookMail As Outlook.MailItem
Set OutlookApp = New Outlook.Application
Set OutlookMail = OutlookApp.CreateItem(olMailItem)
With OutlookMail
.BodyFormat = olFormatHTML
.Display
.HTMLBody = "Hi Team " & "<br>" & "<br>" & "Request you to kindly share 
your actions on each of your follow up items by 8 PM today." & .HTMLBody

.To = "[email protected];[email protected];[email protected]"
.Subject = "Team Follow Up"
.Send

End With
End Sub

VBA Outlook Example 2-1

After running the macro, you will see the mail has been sent automatically from your outlook.

Example to send Email

Things to Remember

  • First, make sure you have installed Microsoft Outlook in your computer and you have login into your account.
  • Make sure that the box for Microsoft Outlook in Object Library reference is always checked. The code will not run and throw an error if it is not checked.
  • Defining variables and setting variables in very important in VBA coding. Without Variables, a code will not work.
  • Make sure that if you want to add signature in the mail, first you should have at least one signature already created in outlook.
  • Always use “<br>” to enter line gaps in the mail.

Recommended Articles

This is a guide to VBA Outlook. Here we discuss how to send emails from Outlook using VBA codes in excel along with an example and downloadable excel template. Below are some useful excel articles related to VBA –

  1. VBA OverFlow Error
  2. VBA Named Range
  3. VBA CLng
  4. VBA Option Explicit

  • Интернет
  • Рассылка почты

Пример макроса, отправляющего письма со вложениями из Excel через почтовый клиент Outlook:

Sub Отправить_Письмо_из_Outlook()
 
    'отправляем письмо без вложений
    res = SendEmailUsingOutlook("name@domain.ru", "Текст письма 1", "Тема письма 1")
    If res Then Debug.Print "Письмо 1 отправлено успешно" Else Debug.Print "Ошибка отправки"
 
 
    'отправляем письмо с 1 вложением
    attach$ = ThisWorkbook.FullName    ' прикрепляем текущий файл Excel
    res = SendEmailUsingOutlook("name@domain.ru", "Текст письма 2", "Тема письма 2", attach$)
    If res Then Debug.Print "Письмо 2 отправлено успешно" Else Debug.Print "Ошибка отправки"
 
 
    'отправляем письмо с несколькими вложениями
    Dim coll As New Collection    ' заносим в коллекцию список прикрепляемых файлов
    coll.Add "C:Documents and SettingsAdminРабочий столTyres.jpg"
    coll.Add "C:Documents and SettingsAdminРабочий столcalc.xls"
    coll.Add ThisWorkbook.FullName    ' прикрепляем текущий файл Excel

    res = SendEmailUsingOutlook("name@domain.ru", "Текст письма 3", "Тема письма 3", coll)
    If res Then Debug.Print "Письмо 3 отправлено успешно" Else Debug.Print "Ошибка отправки"
End Sub

Макрос использует функцию SendEmailUsingOutlook, которая:

  • принимает в качестве параметров адрес получателя письма, тему и текст письма, список вложений
  • запускает Outlook, формирует письмо, и отправляет его
  • возвращает TRUE, если отправка прошла успешно, или FALSE, если с отправкой почты вызникли проблемы

Код функции SendEmailUsingOutlook:

Function SendEmailUsingOutlook(ByVal Email$, ByVal MailText$, Optional ByVal Subject$ = "", _
                               Optional ByVal AttachFilename As Variant) As Boolean
    ' функция производит отправку письма с заданной темой и текстом на адрес Email
    ' с почтового ящика, настроенного в Outlook для отправки писем "по-умолчанию"
    ' Если задан параметр AttachFilename, к отправляемому письму прикрепляется файл (файлы)

    On Error Resume Next: Err.Clear
    Dim OA As Object: Set OA = CreateObject("Outlook.Application")
    If OA Is Nothing Then MsgBox "Не удалось запустить OUTLOOK для отправки почты", vbCritical: Exit Function
 
    With OA.CreateItem(0)   'создаем новое сообщение
        .To = Email$: .Subject = Subject$: .Body = MailText$
        If VarType(AttachFilename) = vbString Then .Attachments.Add AttachFilename
        If VarType(AttachFilename) = vbObject Then    ' AttachFilename as Collection
            For Each file In AttachFilename: .Attachments.Add file: Next
        End If
        For i = 1 To 100000: DoEvents: Next    ' без паузы не отправляются письма без вложений
        Err.Clear: .Send
        SendEmailUsingOutlook = Err = 0
    End With
    Set OutApp = Nothing
End Function

Пример макроса, с получением параметров письма из ячеек листа Excel: 

Sub Отправить_Письмо_из_Outlook()
    ' адрес получателя - в ячейке A1, текст письма - в ячейке A2
    res = SendEmailUsingOutlook(Cells(1, 1), Range("a2"), "Тема письма 1")
    If res Then Debug.Print "Письмо 1 отправлено успешно" Else Debug.Print "Ошибка отправки"
End Sub
  • 176198 просмотров

Не получается применить макрос? Не удаётся изменить код под свои нужды?

Оформите заказ у нас на сайте, не забыв прикрепить примеры файлов, и описать, что и как должно работать.

Return to VBA Code Examples

This tutorial will show you how to send emails from Excel through Outlook using VBA.

Sending the Active Workbook

Function SendActiveWorkbook(strTo As String, strSubject As String, Optional strCC As String, Optional strBody As String) As Boolean
   On Error Resume Next
   Dim appOutlook As Object
   Dim mItem As Object
'create a new instance of Outlook
   Set appOutlook = CreateObject("Outlook.Application")
   Set mItem = appOutlook .CreateItem(0)
   With mItem 
     .To = strTo
     .CC = ""
     .Subject = strSubject
     .Body = strBody
     .Attachments.Add ActiveWorkbook.FullName
'use send to send immediately or display to show on the screen
    .Display 'or .Send
   End With
'clean up objects
  Set mItem = Nothing
  Set appOutlook = Nothing
End Function

The function above can be called using the procedure below

Sub SendMail()
   Dim strTo As String
   Dim strSubject As String
   Dim strBody As String
'populate variables
   strTo = "jon.smith@gmail.com"
   strSubject = "Please find finance file attached"
   strBody = "some text goes here for the body of the email"
'call the function to send the email
   If SendActiveWorkbook(strTo, strSubject, , strBody) = true then
      Msgbox "Email creation Success"
   Else
      Msgbox "Email creation failed!"
   End if
End Sub

vba outlook email

Using Early Binding to refer to the Outlook Object Library

The code above uses Late Binding to refer to the Outlook Object. You can add a reference to Excel VBA, and declare the Outlook application and Outlook Mail Item using Early Binding if preferred. Early Binding makes the code run faster, but limits you as the user would need to have the same version of Microsoft Office on their PC.

Click on the Tools menu and References to show the reference dialog box.

vba outlook add reference

Add a reference to the Microsoft Outlook Object Library for the version of Office that you are using.

vba outlook references

You can then amend your code to use these references directly.

vba outlook early binding

A great advantage of early binding is the drop down lists that show you the objects that are available to use!

Sending a Single Sheet from the Active Workbook

To send a single sheet, you first need to create a new workbook from the existing workbook with just that sheet in it, and then send that sheet.

Function SendActiveWorksheet(strTo As String, strSubject As String, Optional strCC As String, Optional strBody As String) As Boolean
   On Error GoTo eh
'declare variables to hold the objects required
   Dim wbDestination As Workbook
   Dim strDestName As String
   Dim wbSource As Workbook
   Dim wsSource As Worksheet
   Dim OutApp As Object
   Dim OutMail As Object
   Dim strTempName As String
   Dim strTempPath As String
'first create destination workbook
   Set wbDestination = Workbooks.Add
   strDestName = wbDestination.Name
'set the source workbook and sheet
   Set wbSource = ActiveWorkbook
   Set wsSource = wbSource.ActiveSheet
'copy the activesheet to the new workbook
   wsSource.Copy After:=Workbooks(strDestName).Sheets(1)
'save with a temp name
   strTempPath = Environ$("temp") & ""
   strTempName = "List obtained from " & wbSource.Name & ".xlsx"
   With wbDestination
      .SaveAs strTempPath & strTempName
'now email the destination workbook
      Set OutApp = CreateObject("Outlook.Application")
      Set OutMail = OutApp.CreateItem(0)
      With OutMail
         .To = strTo
         .Subject = strSubject
         .Body = strBody
         .Attachments.Add wbDestination.FullName
'use send to send immediately or display to show on the screen
         .Display 'or .Display
      End With
      .Close False
  End With
'delete temp workbook that you have attached to your mail
   Kill strTempPath & strTempName
'clean up the objects to release the memory
   Set wbDestination = Nothing
   Set wbSource = Nothing
   Set wsSource = Nothing
   Set OutMail = Nothing
   Set OutApp = Nothing
Exit Function
eh:
   MsgBox Err.Description
End Function

and to run this function, we can create the following procedure

Sub SendSheetMail()
   Dim strTo As String
   Dim strSubject As String
   Dim strBody As String
   strTo = "jon.smith@gmail.com"
   strSubject = "Please find finance file attached"
   strBody = "some text goes here for the body of the email"
   If SendActiveWorksheet(strTo, strSubject, , strBody) = True Then
      MsgBox "Email creation Success"
   Else
      MsgBox "Email creation failed!"
   End If
End Sub

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
vba save as

Learn More!

This is a guest post by Vijay, our in-house VBA Expert.

Send mails using Excel VBA and Outlook - how to

In this article we well learn how to use VBA and Microsoft Outlook to send emails with your reports as attachment.

Scenario

We have an excel based reporting template for the Customer Service Dashboard. We want to update this template using VBA code to create a static version and email it to a list of people. We will define the recipient list in a separate sheet.

Features

1. Code will automatically create necessary folders to save the output file.
2. Email sheet to contain the list of people who are going to receive the report.
3. Sending mail using Microsoft Outlook, primary target is corporate people who are using Outlook as their mail program.

 

 
On our VBA project we would need to add references to the below
1. Microsoft Outlook Object Library
2. Microsoft Scripting Runtime Library
Please note the Outlook library will be available depending on the version of Microsoft Outlook installed on your system, in the example workbook the reference is towards version 14 as available with Outlook 2010. If you have a different version of Outlook installed on your system, you need to point to the correct library installed.

 

 
We have assumed the data used to create the report is already available in the sheet called “rawData”.
We have then updated the “rawData” sheet with 2 new columns having the Date and Time.
Date has been calculated in the rawData sheets using the Date Function.
=DATE(YEAR(B2),MONTH(B2),DAY(B2))
The time has been calculated by converting the actual time of the call into the relevant 30 minute interval.
=INT((TIME(HOUR(B2),MINUTE(B2),SECOND(B2)))/(1/48))*(1/48)
If you need to setup your report into 15 minutes interval then replace 1/48 with 1/96.
We have then used the COUNTIFS and SUMIFS function to create the data view in the Interval Data sheet.

 

Understanding the VBA code to send mails

I will be discussing only the key elements of the code here.

Sheets(Array("Cover", "Interval Data", "rawData")).Copy

This list will create a new workbook containing the 3 sheets that we have included within the Array() parameter. If your report has more sheets feel free to add them.

Set objfile = New FileSystemObject

If objfile.FolderExists(xDir & xMonth) Then
If objfile.FileExists(xPath) Then
objfile.DeleteFile (xPath)
newWB.SaveAs Filename:=xPath, FileFormat:=xlOpenXMLWorkbook, Password:="", WriteResPassword:="", ReadOnlyRecommended:=False _
, CreateBackup:=False

Application.ActiveWorkbook.Close
Else
newWB.SaveAs Filename:=xPath, FileFormat:=xlOpenXMLWorkbook, Password:="", WriteResPassword:="", ReadOnlyRecommended:=False _
, CreateBackup:=False
Application.ActiveWorkbook.Close
End If
Else
xNewFolder = xDir & xMonth
MkDir xNewFolder
newWB.SaveAs Filename:=xPath, FileFormat:=xlOpenXMLWorkbook, Password:="", WriteResPassword:="", ReadOnlyRecommended:=False _
, CreateBackup:=False
Application.ActiveWorkbook.Close
End If

The above code checks if the correct folder exists for the report to be saved or not and creates one if not existing. This also takes cares of overwriting the existing report in case you need to re-run the report again during the same day.
Creating the List of recipients

currentWB.Activate
Sheets("Email").Visible = True
Sheets("Email").Select

strEmailTo = ""
strEmailCC = ""
strEmailBCC = ""

xStp = 1

Do Until xStp = 4
Cells(2, xStp).Select
Do Until ActiveCell = ""
strDistroList = ActiveCell.Value
If xStp = 1 Then strEmailTo = strEmailTo & strDistroList & "; "
If xStp = 2 Then strEmailCC = strEmailCC & strDistroList & "; "
If xStp = 3 Then strEmailBCC = strEmailBCC & strDistroList & "; "
ActiveCell.Offset(1, 0).Select
Loop
xStp = xStp + 1
Loop

The above code will create the list of people for whom the report is intended. We make use of the Do Until Loop here to update the 3 variables to hold the TO, CC and BCC list. The actual email addresses are captured from the Email sheet of the report template.
Please note: there should be no blanks in the list when you are defining the same.

Set olApp = New Outlook.Application
Dim olNs As Outlook.Namespace
Set olNs = olApp.GetNamespace("MAPI")
olNs.Logon
Set olMail = olApp.CreateItem(olMailItem)
olMail.To = strEmailTo
olMail.CC = strEmailCC
olMail.BCC = strEmailBCC
olMail.Subject = Mid(xFile, 1, Len(xFile) - 4)
olMail.Body = vbCrLf & "Hello Everyone," _
& vbCrLf & vbCrLf & "Please find attached the " & Mid(xFile, 1, Len(xFile) - 4) & "." _
& vbCrLf & vbCrLf & "Regards," _
& vbCrLf & "Chandoo.Org"

The above code creates a new instance of Outlook and then logs in to your default mailbox, using which we will be sending the mail out to the recipients. We also create the body of the mail and specify the To, CC and BCC list.

olMail.Attachments.Add xPath
olMail.Display

Finally we add the attachment to the email we have created and then using the Display method bring it on the screen. You may also use the .Send method to send the mail directly.
That is all the code we needed to create a copy of the report with selected few sheets and then send them out using VBA. There are a lot of other methods using which you may be able to send out mails, however this specifically helps out to create report templates to use within your organization and send out mails.
Do you also use VBA and Other methods to send mails, if yes please share the same for the benefit of everyone.

Download Excel File

Click here to download the file & save it on your system and use it to understand this technique.

Do you use Excel to automate emails?

I often use Excel to automatically email reports & messages. This is quite useful when you have to send a snapshot of a report to a large team, but need to customize the email for each recipient.
What about you? Have you used Excel to automate emails? What is your experience like? Do you use VBA or some other technique? Please share using comments.

More on VBA & Macros

If you want to learn more about using VBA to automate reporting & email tasks, read these:

  • Automatically Generate Report Variations using Excel
  • Birthday Reminder & Email in Excel
  • What is VBA & Macros? Introduction
  • Excel VBA Example Macros
  • VBA tutorial videos

Join our VBA Classes

If you want to learn how to develop applications like these and more, please consider joining our VBA Classes. It is a step-by-step program designed to teach you all concepts of VBA so that you can automate & simplify your work.

Click here to learn more about VBA Classes & join us.


Share this tip with your colleagues

Excel and Power BI tips - Chandoo.org Newsletter

Get FREE Excel + Power BI Tips

Simple, fun and useful emails, once per week.

Learn & be awesome.




  • Ask a question or say something…




  • Tagged under

    advanced excel, advanced vba, downloads, email, learn, macros, outlook, screencasts, VBA




  • Category:

    Automation, Excel Howtos, Learn Excel, VBA Macros

Welcome to Chandoo.org

Thank you so much for visiting. My aim is to make you awesome in Excel & Power BI. I do this by sharing videos, tips, examples and downloads on this website. There are more than 1,000 pages with all things Excel, Power BI, Dashboards & VBA here. Go ahead and spend few minutes to be AWESOME.

Read my story • FREE Excel tips book

Advanced Excel & Dashboards training - Excel School is here

Excel School made me great at work.

5/5

Excel formula list - 100+ examples and howto guide for you

From simple to complex, there is a formula for every occasion. Check out the list now.

Calendars, invoices, trackers and much more. All free, fun and fantastic.

Advanced Pivot Table tricks

Power Query, Data model, DAX, Filters, Slicers, Conditional formats and beautiful charts. It’s all here.

Still on fence about Power BI? In this getting started guide, learn what is Power BI, how to get it and how to create your first report from scratch.

Related Tips

55 Responses to “Send mails using Excel VBA and Outlook”

  1. I’ve written code for Excel to email Commission Statements to Sales People each month — so the commission is firstly calculated using a combination of Access (to manipulate Raw Data from a Mainframe System) and Excel (to put this data into a readable format and calculate commission due — each sales person then has his/her own statement). VBA is then used to run through a list of Sales People, attach the relevant spreadsheet file (sometimes zipping 2 or more files for Sales Team Managers etc) and email to the relevant sales person with a bespoke email message.
    This used to be a manual task and take a small team the best part of an afternoon to manual complete.
    VBA is fantastic in these situations.

    • Kelly says:

      THIS IS EXACTLY WHAT I AM TRYING TO DO ! I need help! Did you use Access to run through the list of people and attach the spreadsheet? Or was this all in excel?

  2. Keijo says:

    Hi Chandoo and once again huge thanks for the website. It’s truelly awesome!

    I was wondering what would be your solution for the notification that Outlook brings up when trying to automatically send the email via VBA? At least I get an notice that a program is trying to automatically send a email on my behalf when I use the .Send method.

      • Keijo says:

        Thanks Vijay and the rest of you all for your tips and advices. They are very much appreciated. I’ve already solved the issue with a application.sendkeys command to send the mail, but it isn’t a very «awesome» solution so I was just wondering about other solutions. I’ll be checking out those links that you all send, thanks!

        • Chris says:

          I use the ExpressClickYes application. The basic version is free and works great for me.

  3. Joe Carsto says:

    For many year, I have used a combination of Excel, Access and Outlook to mail various reports to the proper team members. I use a combination of my own VBA code and email code from http://www.rondebruin.nl/sendmail.htm to help automate the process. I use data from the Excel sheets to determine things like: email suject, email priority, the body of the email, etc. I’ve used this method for so long, I don’t know if I could do it manually any longer.

    • Subu says:

      thanks a ton for the link to this website

      that website is awesome !!! such beautiful programs for sending mail with / without attachments

      regards
      Subu
       

  4. Hi Vijay,

    Nice stuff, and super handy. I’ve been emailing reports from Excel for years, and finally got tired of writing the full blown code each project.

    I created a class module to make this much easier, which may be of some interest to your users. It’s late bound, so no need to set any references, and works with all versions of Outlook. The frame to set up an email becomes very easy as well.

    You can find it here if you’re interested: http://www.excelguru.ca/content.php?249-Easy-Outlook-Email-Integration

  5. Bryan C says:

    I email several reports and dashboards to several people each day. I prefer to simply send «screenshots» (using greenshot or similar) in the body on the email rather than trying to inserct worksheet ranges and what not particulary when sending charts.

    I have been unable to find a good source of vba to automate this procedure. Everyting I can find only captures worksheet ranges instead of screen captures ( just part of the screen, like when you use the crosshairs in greenshot). If anyone has vba that will capute a partial screenshot based on screen coordinates along with the code to paste that screenshot into an outlook body I would greatly indebted.
    Thanks in advance

    • NM says:

      Steve Bullen’s code comes in very handy for selecting particular sections from a worksheet, copy those to dashboard and then pasting them wherever you need. You can find it at http://www.oaltd.co.uk/excel/default.htm; look for PastePicture.zip. Works like a charm…

  6. dan l says:

    I’ve used the outmail thing for mailing gadgets for quite sometime.

  7. René says:

    I’ve been using a combination of Access, Excel and Outlook to send the reports for some years now. As the data and manipulation of data is straightforward, I always do the manipulation in Access. I have to generate my reports each month, and Access gives me the structure to manipulate without copying formulas etc. Once built, it works for all new added data. And while doing, you build a history. That has proven a good thing as well.
    The final report is created in (or exported to) Excel, and send with Outlook. VBA makes it possible to do this without leaving Access.
    @Keijo: I used to run a little program called ClickYes to get rid of the Outlook notifications. You can call this program from VBA as well. That was in Office 2003 days.
    @Joe: There’s a lot of useful VBA examples around, and Ron de Bruin is one of my favorite places to go, as is Chandoo’s since the last year or so.

  8. Bryan C says:

    Hi Rene,
    I agree that Ron DeBruin’s site has the best source of code all in one place for vba to email excel.

    The one thing missing is the ability to email partial screenshots in an outlook body.
    This is really what I need!

  9. Doug Hoover says:

    I use Excel and VBA with Novel GroupWise to email task update notifications from a spreadsheet we use for task tracking (Thanks to Chandoo a few years ago for some of the ideas from a TODO LIST posting). The program manager or supervisor can add a task to the job list (each person has a separate worksheet in the shared workbook) then select the rows with the new additions and run the macro. The «canned» e-mail is created with an additional message from the manager and sent to the individual and supervisor with only the updated tasks numbered and listed.
    I don’t send the entire worksheet only the contents of the rows and a special few of the columns selected. Not perfect in automation but it works very well manually.
    We have just changed to IBM Lotus Notes and I need to change the VBA code next week, so this post is right on time to keep me thinking straight. I have already found the VBA references I need to change to make NOTES work but it is always good to review the basics.
    Thanks again Chandoo and Vijay.

  10. Chandoo, you really need some kind of syntax highlighter.

    Vijay, thanks for posting this code. I’m confused about a couple of things. Your code has Format(xDate, «mm mmmm yy») in it, I think you meant Format(xDate, «dd mmmm yy»)? Why do you check if a file exists before deleting it? Also, why do you use FSO instead of ‘Dir’ and ‘Kill’ when you already use ‘MkDir’? Thanks for your time.

    • Vijay Sharma says:

      @JP,

      Thanks for pointing out the «dd», a typo from me on this.

      As you can see the report was desinged at 30 minutes interval and if you needed to run the report multiple times during the day, it would be unnecessary to create multiple copies of the same, hence the delete code.

      FSO is used to bring another object for people to learn, as a lot of time people do not know what are the objects / libraries that exist and how to make use of them.

      ~VijaySharma

      • Vijay…Help! I need to have the file saved in a folder in another directory! «O:Profitability2016» How do I do this? Where do I change it in the code? I would like the file name to be in the same format. Right now the macro is telling it to create a folder to save the file in the same place as the template file. I want the created folder to save in that directory on the network. Help!! Thanks!!!

  11. Kevin F says:

    I’ve been using Excel to send meeting notices to our annual internal technical conference attendees.  I get an extract of the data from our registration system, then sort the data by technical session.  Each session is 1 or 2 hours, and there are 3 days of sessions. 

    I then use VBA to build a meeting notice and add the attendees names to the meeting notice.  The notice shows the data and time of the session, along with the room location.  The nice part about this is that each technical session is then put in everyone’s calendar. 

    Since I am the originator of the meetings, I can easily send updates to the attendees if anything about the session changes (i.e, room location changes).  Attendees can also see their entire schedule in outlook and on their smart phones.  To do this manually would be nearly impossible.  The VBA program sends out thousands of meeting notices in a few minutes through this automated process, and it works flawlessly.

  12. […] enjoy reading articles about interop between Outlook and Excel using VBA code. So I read the recent guest post on Chandoo’s site with interest. I downloaded the sample workbook to study the code, and I suggest you do the same. […]

  13. Ben B says:

    I have used the VBA in Excel 2007 to send emails for bulk emails that I need, has significantly increased my productivity.
    The Outlook version I have is 2007.  For every email that the XLS tries to send I have to «Allow/Deny» is there a way to remove this «security» feature to allow the email/s to be directly sent w/o user intervention?

  14. Luis Boy says:

    Hi everbody, I’m looking for a macro that would allow me to email thet active worksheet but that the email address is not hard coded; something that allows me enter the email address before sending it.

    Any help would be very much appreciated

  15. Ram says:

    Hi sir,

    I have tried for send mail using Excel, but When I am trying to add
    5 mailing ids in the «CC» column it’s showing #value error message.
    Please suggest how to send mail more than 4 or 5 people at a time.

    Thanks,
    ram 

  16.  
    I am really amazed. Today I spent a lot of time searching for something interesting on this topic. Finally I found your blog. Thanks for that!
    <a href=»http://medcaremso.com»><b>Medical Billing Services</b></a>
     

  17. John W says:

    I have several basic email messages saved as xxx.msg files from outlook. I use these as templates for emailing some specific items. I’d like to incorporate the use of the the .msg file (basically just the body). I can’t seem to get it to work. Any thoughts?
    Thanks,
    John

  18. Thanks for providing detailed information about email sending though Excel VB & outlook.

    Open Multiple URL

  19. Ameila says:

    Thanks for the post. I have been using a program that i found at http://insightaz.com/. They helped me the first time and then when i has reoccurring reports to be done they helped me set up a system that i could use each time a report was needed.

  20. Hi Chandoo,

    Nice one, if we are using lotus notes than what changes needs to made in vba. Please let me know.

    Regards,
    Rayudu

  21. Binaya says:

    I have followed tutorial guidelines and succeed to send email thru Outlook express 2010. But when I used same codes and try to send email on Outlook 2007 it is showing error. Can someone help me how to debug error, I am novice and do not understand much concept. I can forward my workbook but dont know how to attach in this forum 🙁

  22. Abby says:

    Hi Vijay,

    Cn you please advice what would be the Vba code for sending email from excel to gmail instead of outlook?

  23. […] Send mails using VBA and Outlook – How to send emails using … – This is a guest post by Vijay, our in-house VBA Expert. In this article we well learn how to use VBA and Microsoft Outlook to send emails with your reports as attachment. […]

  24. George says:

    Hi Vijay,

    I have tried to use your vb code in order to send an email from excell, however get the following «Compile error» when trying to run the code:

    «User defined type not defined» and points to the following section in your code:

    Dim olApp As Outlook.Application

    Please note that i am a novice when it comes to the use of VB code in excel, however am able to follow some of the logic if explained in laymens terms:)

    I would very much appreciate your assistance or some direction to resolve.

    kind regards
    George

  25. […] Send mails using VBA and Outlook – How to send emails using … – Ever wondered how we can use Excel to send emails thru Outlook? We can use Excel VBA Macros to send emails to others thru Outlook. Scenario: We have an excel […]

  26. Jerry says:

    I have a VBA code that helps me send all of my reports via e-mail in Excel. Send single worksheet as an attachment from Excel with VBA code: Excellent VBA Code. Works GREAT !!!

    Instead of entering the To: & CC: e-mails manually, I want to pull the e-mail addresses from a separate worksheet called «E-Mail List». The (a1) has the «To» e-mail address and (b1) has the «CC» e-mail address. I know this is relatively simple to solve but I cannot figure out what I am doing wrong.

    Thank you everyone in advance.

    Wb2.SaveAs FilePath & FileName & xFile, FileFormat:=xFormat
    With OutlookMail
    .To = «thatdudesname@thatdudescompany.com»
    .CC = «»
    .BCC = «»
    .Subject = «kte features»
    .Body = «Please check and read this document.»
    .Attachments.Add Wb2.FullName
    .Send
    End With
    Wb2.Close
    Kill FilePath & FileName & xFile
    Set OutlookMail = Nothing
    Set OutlookApp = Nothing
    Application.ScreenUpdating = True
    End Sub

  27. Anoop Nair says:

    Hi Team,

    I am into MIS reporting and wanted a help in automating a report.
    i have a report in which 73 report need to be send and for each report i want he excel content to be pasted on my mail body and the excel to be attached. for the same i have written 73 macro codes for each individual report.
    Now its a manual activity to send each report daily so i wanted to know is there any possible way where i can automate to the fullest way so that it makes my job easier.

    Need your help.

    Anoop

  28. why i cannot run this there is always an error at the side of declaring the variables…

    in outlook.application

  29. Anjan Barua says:

    Hi,

    Is there any possible way to create a hyperlink of inbox mail with excel, so by click to the excel the particular mail can be opend.

  30. Pallab says:

    I am trying to send an html page embedding it in the mail body. I have used the htmlbody property of mailitem. But when i use the .htm file in this property the actual mail body shows the file not found error. Can anyone pleaee help with a piece of vba code to resolve this?

  31. i need to reply the outook mail. search mail using subject and earliaset mail. please help. need to do this from vba code on excel macro

  32. Shafaat says:

    Hi team Any one help me out to rectified this need to change lotus mail converted into outlook how can we use this thru out look please help

    vb code given below

    Sub sendmail()

    ‘ sendmail Macro

    Dim dte As Date
    Dim mon As Integer
    Dim yr As Integer
    Dim mailcount As Integer
    Dim filtercol As Integer
    Dim Maildb As Object
    Dim MailDoc As Object
    Dim attachME As Object
    Dim Session As Object
    Dim EmbedObj1 As Object
    Dim UserName As String
    Dim MailDbName As String
    Dim recipient As String
    Dim ccRecipient As String
    Dim bccRecipient As String
    Dim subject As String
    Dim finlsub As String
    Dim stSignature As String
    Dim addname As String
    Dim bodytext As String
    Dim Attachment1 As String
    Dim Attachment2 As String
    Dim FilName As String
    Application.DisplayAlerts = False
    dte = Date
    mon = Month(dte)
    yr = Year(dte)
    Attachment2 = Range(«F15»).Value
    Sheets(«MAIL-ID»).Activate
    Range(«AG2»).Value = 0
    mailcount = Range(«AG14»).Value
    subject = Range(«F2»).Value
    bodytext = Range(«F6»).Value & Chr(10) & Range(«F7»).Value & Chr(10) & Range(«F8»).Value & Chr(10) & Range(«F9»).Value & Chr(10) & Range(«F10»).Value & Chr(10)
    addname = Range(«F12»).Value
    If mon = 12 Then GoTo exitsub
    exitsub: If UCase(Environ$(«USERDOMAIN»)) «ONEAIRTEL» Then MsgBox «This is not your copy of Filtermails » & Chr(10) & «You are an UNAUTHORISED USER «, vbCritical
    Exit Sub
    validated: If mailcount = 0 Then MsgBox «There are no recepients in your list.», vbCritical, «WHAT ARE YOU DOING?»
    For x = 0 To (mailcount — 1)
    Sheets(«MAIL-ID»).Select
    Range(«AG2»).Value = x + 1
    FilName = (Environ$(«temp»)) & «temp.xls»
    If Dir(FilName) «» Then
    Kill FilName
    End If
    filtercol = Range(«F4»).Value
    Range(«AG4»).Select
    Selection.Copy
    Range(«AG7»).Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
    Application.CutCopyMode = False
    recipient = Range(«AG7»).Value
    Range(«AG5»).Select
    Selection.Copy
    Range(«AG8»).Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
    Application.CutCopyMode = False
    ccRecipient = Range(«AG8»).Value
    If ccRecipient = «0» Then
    ccRecipient = «»
    End If
    Range(«AG6»).Select
    Selection.Copy
    Range(«AG9»).Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
    Application.CutCopyMode = False
    bccRecipient = Range(«AG9»).Value
    If bccRecipient = «0» Then
    bccRecipient = «»
    End If
    Range(«AG3»).Select
    Selection.Copy
    Range(«AG11»).Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
    Application.CutCopyMode = False
    Range(«AG11»).Copy (Sheets(«DATA»).Range(«O60000»))
    Sheets(«DATA»).Select
    If addname = «YES» Then
    finlsub = subject & » ( » & Range(«O60000″).Value & » )»
    finlbody = «Dear » & Range(«O60000»).Value & Chr(10) & Chr(10) & bodytext
    End If
    If addname = «NO» Then
    finlsub = subject
    finlbody = bodytext
    End If
    Range(«A1»).Select
    If Range(«a1») = «» Then
    MsgBox «NO or Wrong arrangement of Data in DATA Sheet», vbCritical
    Exit For
    End If
    Selection.AutoFilter
    Selection.AutoFilter field:=filtercol, Criteria1:= _
    Range(«O60000»).Value
    Range(«A1»).Select
    Range(Selection, Selection.End(xlDown)).Select
    Range(Selection, Selection.End(xlToRight)).Select
    Selection.Copy
    Workbooks.Add
    ActiveSheet.Paste
    Cells.Select
    Cells.EntireColumn.AutoFit
    ActiveWorkbook.SaveAs Filename:=FilName, FileFormat:= _
    xlNormal, Password:=»», WriteResPassword:=»», ReadOnlyRecommended:=False _
    , CreateBackup:=False
    ActiveWorkbook.Close
    Set Session = CreateObject(«Notes.NotesSession»)
    UserName = Session.UserName
    MailDbName = Left$(UserName, 1) & Right$(UserName, (Len(UserName) — InStr(1, UserName, » «))) & «.nsf»
    Set Maildb = Session.GETDATABASE(«», MailDbName)
    If Maildb.IsOpen True Then
    On Error Resume Next
    Maildb.OPENMAIL
    End If
    Set MailDoc = Maildb.CreateDocument
    MailDoc.form = «Memo»
    stSignature = Maildb.GetProfileDocument(«CalendarProfile») _
    .GetItemValue(«Signature»)(0)
    With MailDoc
    .SendTo = recipient
    .copyto = ccRecipient
    .blindcopyto = bccRecipient
    .subject = finlsub
    .body = finlbody & vbCrLf & vbCrLf & stSignature
    End With
    MailDoc.SaveMessageOnSend = True
    Attachment1 = FilName
    If Attachment1 «» Then
    Set attachME = MailDoc.CREATERICHTEXTITEM(«Attachment1»)
    Set EmbedObj1 = attachME.EmbedObject(1454, «», Attachment1, «Attachment»)
    Set EmbedObj2 = attachME.EmbedObject(1454, «», Attachment2, «Attachment»)
    MailDoc.CREATERICHTEXTITEM («Attachment»)
    End If
    MailDoc.PostedDate = Now()
    MailDoc.send 0, recipient
    Set Maildb = Nothing
    Set MailDoc = Nothing
    Set attachME = Nothing
    Set Session = Nothing
    Set EmbedObj1 = Nothing
    finlsub = Null
    finlbody = Null
    Next
    Sheets(«MAIL-ID»).Activate
    Range(«A1»).Select
    MsgBox «Thank you for using this MACRO»
    End Sub

  33. kuldeep says:

    Can any one help me to create one macro.

    My work is very simple I need to send multiple email from excel in my excel there are multiple list of to email and cc email excel also contain subject and body of email.

    All this is my requirement.

    • @Kuldeep

      This has been asked several times and so using the Search Box at the Top Right of each screen may be a good place to start

      If that doesn’t help I’d suggest asking the question in the Chandoo.org Forums http://forum.chandoo.org/
      Attach a sample file with an example of what you are after

  34. Lucrecia Mahmood says:

    Invaluable discussion . I am thankful for the points — Does anyone know where my business could acquire a fillable NY DTF ST-330 copy to work with ?

  35. Devendra Prakash Jalan says:

    I want to send multiple mails, different different data to different different person using one VBA/Macro, is it possible?

    • Diederik says:

      check my post from today, answer is Yes.
      it needs some serouis work/thinking
      But if you have 1 report for x entities you can send them to each entity one by one with VBA. After pushing the button you will barely have time for tea 🙂

  36. Can someone help me? I have the code working perfectly with my sheet. However…… I need all the amail features but I need the file to attach as PDF not as an excel file. Again, I need all the features with the email automation, saving the email attachment with the cell reference. Please view my code and tell me how It can attach as a pdf instead of an excel file. Thanks!!!!

    Option Explicit

    Sub ExportEmail()

    Dim objfile As FileSystemObject
    Dim xNewFolder
    Dim xDir As String, xMonth As String, xFile As String, xPath As String
    Dim OlApp As Outlook.Application
    Dim OlMail As Outlook.MailItem
    Dim NameX As Name, xStp As Long
    Dim xDate As Date, AWBookPath As String
    Dim currentWB As Workbook, newWB As Workbook
    Dim strEmailTo As String, strEmailCC As String, strEmailBCC As String, strDistroList As String
    Dim ws As Worksheet

    AWBookPath = ActiveWorkbook.Path & «»

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    Application.StatusBar = «Creating Email and Attachment for » & Format(Date, «dddd dd mmmm yyyy»)

    Set ws = Worksheets(«Control»)
    Set currentWB = ActiveWorkbook

    xDate = Date

    ‘******************************Grabbing New WorkBook and Formatting*************

    Sheets(Array(«Control»)).Copy

    Set newWB = ActiveWorkbook

    Range(«A1»).Select

    Sheets(«Control»).Select

    ‘******************************Creating Pathways*********************************

    xDir = AWBookPath
    xMonth = Format(xDate, «mm mmmm yy») & «»

    xFile = «Business Trip — Request Form for » & Range(«b7″).Text & » » & Format(xDate, «mm-dd-yyyy») & «.xlsx»

    xPath = xDir & xMonth & xFile

    ‘******************************Saving File in Pathway*********************************

    Set objfile = New FileSystemObject

    If objfile.FolderExists(xDir & xMonth) Then
    If objfile.FileExists(xPath) Then
    objfile.DeleteFile (xPath)
    newWB.SaveAs Filename:=xPath, FileFormat:=xlOpenXMLWorkbook, Password:=»», WriteResPassword:=»», ReadOnlyRecommended:=False _
    , CreateBackup:=False

    Application.ActiveWorkbook.Close
    Else
    newWB.SaveAs Filename:=xPath, FileFormat:=xlOpenXMLWorkbook, Password:=»», WriteResPassword:=»», ReadOnlyRecommended:=False _
    , CreateBackup:=False
    Application.ActiveWorkbook.Close
    End If
    Else
    xNewFolder = xDir & xMonth
    MkDir xNewFolder
    newWB.SaveAs Filename:=xPath, FileFormat:=xlOpenXMLWorkbook, Password:=»», WriteResPassword:=»», ReadOnlyRecommended:=False _
    , CreateBackup:=False
    Application.ActiveWorkbook.Close
    End If

    ‘******************************Preparing Distribution List *********************************

    currentWB.Activate
    Sheets(«Email»).Visible = True
    Sheets(«Email»).Select

    strEmailTo = «»
    strEmailCC = «»
    strEmailBCC = «»

    xStp = 1

    Do Until xStp = 4

    Cells(2, xStp).Select

    Do Until ActiveCell = «»

    strDistroList = ActiveCell.Value

    If xStp = 1 Then strEmailTo = strEmailTo & strDistroList & «; «
    If xStp = 2 Then strEmailCC = strEmailCC & strDistroList & «; «
    If xStp = 3 Then strEmailBCC = strEmailBCC & strDistroList & «; «

    ActiveCell.Offset(1, 0).Select

    Loop

    xStp = xStp + 1

    Loop

    Range(«A1»).Select

    ‘******************************Preparing Email*********************************

    Set OlApp = New Outlook.Application
    Dim olNs As Outlook.Namespace
    Set olNs = OlApp.GetNamespace(«MAPI»)
    olNs.Logon
    Set OlMail = OlApp.CreateItem(olMailItem)
    OlMail.To = strEmailTo
    OlMail.CC = strEmailCC
    OlMail.BCC = strEmailBCC

    OlMail.Subject = Mid(xFile, 1, Len(xFile) — 4)
    OlMail.Body = vbCrLf & «Hello,» _
    & vbCrLf & vbCrLf & «Please find attached the » & Mid(xFile, 1, Len(xFile) — 4) _
    & vbCrLf & vbCrLf & «Regards,» _
    & vbCrLf & vbCrLf & ws.Range(«b7»).Value

    OlMail.Attachments.Add xPath
    OlMail.Display

    Application.StatusBar = False
    Application.ScreenUpdating = True
    Application.DisplayAlerts = True

    End Sub

    • Diederik says:

      Hi Laura, you can use «ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF» etc to save your current sheet as PDF. If you store the filename in a variable like «PDFfile» (DIM as String) you can use that name to attach the PDF in your mail.
      Looks somewhat like this:
      Dim blabla
      Thisfile = Range(«S1»).Value
      PDFFile = DestFolder & Application.PathSeparator & Thisfile & «.pdf»
      ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=PDFFile, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False

      then you have your PDF file on a serverlocation and you can attach it to a mail

  37. I need to change the code bellow to save as .xlsm. I need the macro to stay with the attached file I am sending. Thi is the code I have so far:

    Set objfile = New FileSystemObject

    If objfile.FolderExists(xDir & xMonth) Then
    If objfile.FileExists(xPath) Then
    objfile.DeleteFile (xPath)
    newWB.SaveAs Filename:=xPath, FileFormat:=xlOpenXMLWorkbook, Password:=»», WriteResPassword:=»», ReadOnlyRecommended:=False _
    , CreateBackup:=False

    Application.ActiveWorkbook.Close
    Else
    newWB.SaveAs Filename:=xPath, FileFormat:=xlOpenXMLWorkbook, Password:=»», WriteResPassword:=»», ReadOnlyRecommended:=False _
    , CreateBackup:=False
    Application.ActiveWorkbook.Close
    End If
    Else
    xNewFolder = xDir & xMonth
    MkDir xNewFolder
    newWB.SaveAs Filename:=xPath, FileFormat:=xlOpenXMLWorkbook, Password:=»», WriteResPassword:=»», ReadOnlyRecommended:=False _
    , CreateBackup:=False
    Application.ActiveWorkbook.Close
    End If

  38. Shreevathsaa Mahadevan says:

    Hi,

    I am trying to send a specific page from a word document through Outlook in Body, I am unable to do. I am able to write a code to send as an attachment. But I need to send it via Body of the email, which will reduce lots of time. Kindly help me in this.

    I wrote a code, which will browse and open a word document. I do no how to select specific page and mail them using Outlook. Please help!

    Sub browse()
    Dim FSO As Object
    Dim blnOpen
    strFileToOpen = Application.GetOpenFilename(Title:=»Please choose a file to open», _
    FileFilter:=»Word Files *.doc* (*.doc*),»)
    If strFileToOpen = False Then
    MsgBox «No file selected.», vbExclamation, «Sorry!»
    Exit Sub
    Else
    Sheet2.Range(«G5»).Value = strFileToOpen
    Set objWord = CreateObject(«Word.Application»)
    Set objDoc = objWord.Documents.Open(strFileToOpen)
    objWord.Visible = True
    End If
    End Sub

  39. Diederik says:

    Hi all,

    I use Excel to generate individual mails to alle Dutch municipalities.
    I have a workbook with a (dashboard) report and financial data from 400 cities. The workbook also contains a list of 400 email adresses (1 or more contactperson(s) for each city).
    After some trial and error work and some serious copy-pasting code from the net I now have the following VBA code working:

    1 run report for city 1
    2 export report as PDF to serverlocation
    3 create mail (text hard coded in VBA — still need easier way…)
    4 attach PDF (and any other attachement if needed)
    4 send mail to contact person (ore 2 or 3)
    5 start again with city 2 > loop for x times (400 in this case but flexible)

    This all runs in 15 minutes where my co-workers were busy for 5 days before I build them this report. I’ve build in a message in the statusbar to tell how many reports of x have been send to follow progress.
    First a quarterly service this has now evolved to a monthly service and I use the tricks I learned for more projects like this.
    I started last year with VBA to automate repetitive tasks for my client. It’s amazing what you can do with a little bit of VBA 🙂

    BTW I’m a big fan of Chandoo!

    Best Regards, Diederik

  40. How do I change the file path to where I want the files saved from being in the same folder as the file?

    I am using the code on this page. I want it sent to another directory. I want the file to stay where it is, but the files that are created I want them to go to «L:»

    This is an easy one. Thanks!

  41. Ranjit Singh Kumar says:

    I have a code to send an email text to the recipient, it works on 32 bit office 2016, however generates a «Microsoft Installer error» in 64 bit office 2016.
    Sub testMail()
    Dim OutApp,outmail As Object
    Set OutApp = CreateObject(«Outlook.Application»)
    Set OutMail = OutApp.CreateItem(0)
    With OutMail
    .To = «r@r.com»
    .Subject = «Reports»
    .HTMLBody = «Hello»
    .Display
    End With
    End Sub
    This code generates error «Microsoft Software Installer error has occurred». I am using Win7 64 bit and office 2016 64 bit. When I click «Debug», it highlights the line «Set OutApp = CreateObject(«Outlook.Application»)». Help!!!!

  42. Swapnil says:

    hi anyone help me for i have 10 telephone no. i need to send to one person one bye one with same subject i need VBA code for that.

Понравилась статья? Поделить с друзьями:
  • Vba excel and or xor not
  • Vba excel and example
  • Vba excel all sheets in workbook
  • Vba excel all pdf
  • Vba excel all opened