Thursday, May 30, 2024

Automating Email with VBA in Excel Macro

Automating Email with VBA

In this blog post, I will walk you through a VBA script that automates the process of sending emails using Outlook. Below is the script and an explanation of how it works:

                
Sub SendEmail()
    Dim OutApp As Object
    Dim OutMail As Object
    Dim ws As Worksheet
    Dim rng As Range
    Dim toEmail() As String
    Dim ccEmail() As String
    Dim subject As String
    Dim body As String
    Dim filePath As String
    Dim i As Long
    
    Set OutApp = CreateObject("Outlook.Application")
    Set ws = ThisWorkbook.Sheets("Sheet1")
    
    For Each rng In ws.Range("A2:A" & ws.Cells(ws.Rows.Count, "A").End(xlUp).Row)
        toEmail = Split(rng.Value, ";")
        ccEmail = Split(rng.Offset(0, 1).Value, ";")
        subject = rng.Offset(0, 2).Value
        body = rng.Offset(0, 3).Value
        filePath = rng.Offset(0, 4).Value
        
        Set OutMail = OutApp.CreateItem(0)
        With OutMail
            ' Add To recipients
            For i = LBound(toEmail) To UBound(toEmail)
                .Recipients.Add toEmail(i)
            Next i
            
            ' Add CC recipients
            For i = LBound(ccEmail) To UBound(ccEmail)
                .Recipients.Add ccEmail(i)
            Next i
            
            .subject = subject
            .body = body
              
            ' Attach file if path is provided
            If filePath <> "" Then
                .Attachments.Add filePath
            End If
                  
            .Send
        End With
        
        Set OutMail = Nothing
    Next rng
    
    Set OutApp = Nothing
End Sub

                
            

Explanation:

  • OutApp and OutMail: These objects are used to interface with Outlook.
  • ws: Refers to the worksheet containing the email data.
  • rng: Loops through each row of data to extract email details.
  • toEmail, ccEmail, subject, body, filePath: Variables to store email details from the worksheet.
  • The script sets the necessary fields for each email and sends it using Outlook.

No comments:

Post a Comment

Featured Post

Construction Result Summary Jun-2019