How to generate a mail using vba in excel

To generate a mail using VBA in Excel, you can use the Outlook.Application and Outlook.MailItem objects. Here's a step-by-step guide:

Prerequisites:

  1. You need to have Outlook installed on your computer.
  2. You need to have the Microsoft Outlook Object Library referenced in your VBA project. To do this, follow these steps:
    • Open the Visual Basic Editor (VBE) by pressing Alt + F11 or by navigating to Developer > Visual Basic in the ribbon.
    • In the VBE, click Tools > References in the menu.
    • Check if Microsoft Outlook Object Library is listed and select it if it's not already checked.
  3. Make sure you have the necessary permissions to send emails using Outlook.

Code:

Here's an example code that generates a mail using VBA in Excel:

Sub SendMail()
    ' Set up Outlook application
    Dim olApp As New Outlook.Application
    Dim olMail As Outlook.MailItem

    ' Create a new mail item
    Set olMail = olApp.CreateItem(olMailItem)

    ' Set the mail properties
    With olMail
       .Subject = "Test Email"
       .Body = "This is a test email sent from Excel using VBA."
       .To = "[email protected]"
       .CC = ""
       .BCC = ""
       .Send
    End With

    ' Clean up
    Set olMail = Nothing
    Set olApp = Nothing
End Sub

How to use the code:

  1. Open the Visual Basic Editor (VBE) by pressing Alt + F11 or by navigating to Developer > Visual Basic in the ribbon.
  2. In the VBE, insert a new module by clicking Insert > Module in the menu.
  3. Paste the code into the module.
  4. Modify the code as needed (e.g., change the subject, body, recipient, etc.).
  5. Click Run > Run Sub/User Form or press F5 to execute the code.
  6. The email will be sent using Outlook.

Tips and variations: