Forum Discussion

Rajan1415's avatar
Rajan1415
Copper Contributor
Jan 23, 2024

Using word Template as outlook mail body

Hello,

 

I have created a VBA macro, referring Ms word doc as outlook mail body. If I am using . display to preview mail it's working however when I update code to .send code fails.

Please share some solution 

5 Replies

  • NikolinoDE's avatar
    NikolinoDE
    Gold Contributor

    Rajan1415 

    When using a Word document as the body of an Outlook email through VBA, there can be some differences in behavior between using .Display and .Send. The issue you're facing might be related to the timing of sending the email. The .Display method allows you to review and make changes to the email before it is sent, while the .Send method sends the email immediately.

    Here is a sample code that you can use as a reference:

    Sub SendEmailWithWordBody()
        Dim OutlookApp As Object
        Dim OutlookMail As Object
        Dim WordApp As Object
        Dim WordDoc As Object
    
        ' Create a new instance of Outlook
        Set OutlookApp = CreateObject("Outlook.Application")
        ' Create a new email
        Set OutlookMail = OutlookApp.CreateItem(0)
    
        ' Create a new instance of Word
        Set WordApp = CreateObject("Word.Application")
        ' Open your Word document
        Set WordDoc = WordApp.Documents.Open("C:\Path\To\Your\Word\Document.docx")
    
        ' Copy the content from Word to Outlook
        WordDoc.Content.Copy
        OutlookMail.BodyFormat = 2 ' olFormatHTML
        OutlookMail.HTMLBody = WordApp.Selection.HTML
    
        ' Additional email properties (To, Subject, etc.)
        OutlookMail.To = "email address removed for privacy reasons"
        OutlookMail.Subject = "Your Subject"
    
        ' Display or Send the email
        ' Uncomment one of the following lines
    
        ' OutlookMail.Display ' Use this line for previewing the email before sending
    
        ' Uncomment the next line for sending the email
        ' OutlookMail.Send
    
        ' Close the Word document and release objects
        WordDoc.Close SaveChanges:=False
        Set WordDoc = Nothing
        Set WordApp = Nothing
    
        ' Release Outlook objects
        Set OutlookMail = Nothing
        Set OutlookApp = Nothing
    End Sub

    In this code:

    • The Word content is copied using WordApp.Selection.HTML and pasted into the HTMLBody of the Outlook email.
    • Make sure to replace "C:\Path\To\Your\Word\Document.docx", "email address removed for privacy reasons", and "Your Subject" with your actual file path, recipient's email address, and subject.
    • The code is set up to either display the email or send it. Comment/uncomment the appropriate line based on your needs.

    Remember to adjust the file path, recipient email, and subject as needed. Also, be cautious when using .Send, as it will send the email immediately without allowing you to review it.

     

    If the issue persists, you may want to check for any error messages that might provide more information on what is going wrong during the .Send operation. Provide additional information about the office version, operating system, storage medium, etc. If possible the existing code. The text, steps and code were created with the help of AI.

     

    My answers are voluntary and without guarantee!

     

    Hope this will help you.

    Was the answer useful? Mark as best response and Like it!

    This will help all forum participants.

    • Rajan1415's avatar
      Rajan1415
      Copper Contributor

      NikolinoDE 

      Thank you  for reverting back, however share code is not working as desired.
      Kindly review my code and share your insights.

       

      Option Explicit
      
      Sub SendMailViaWord()
          On Error GoTo ErrorHandler
          
          Dim OutApp As Outlook.Application
          Dim OutMail As Outlook.MailItem
          Dim OutAccount As Outlook.Account
          Dim Subject As String
          Dim UserName As String
          Dim WordApp As Object
          Dim WordDoc As Object
          Dim WordFilePath As String
          Dim LastRow As Long
          Dim i As Long
      
          ' Set the Outlook application object
          Set OutApp = CreateObject("Outlook.Application")
          
          ' Set the Word application object
          Set WordApp = CreateObject("Word.Application")
          WordApp.Visible = False
      
          ' Define the mail subject from cell B1
          Subject = Sheets("Sheet1").Range("B1").Value
          
          ' Define the Word file path from cell B2
          WordFilePath = Sheets("Sheet1").Range("B2").Value
      
          ' Find the last row with data in column A (Names)
          LastRow = Sheets("Sheet1").Cells(Sheets("Sheet1").Rows.Count, "A").End(xlUp).Row
      
          ' Loop through the rows starting from row 6 (assuming headers are in row 4)
          For i = 6 To LastRow
              ' Get the username from the Name column (Column A)
              UserName = Sheets("Sheet1").Cells(i, 1).Value
      
              
              ' Create a new email
              Set OutMail = OutApp.CreateItem(olMailItem)
              
              'Use the ccount based on the number
              Set OutAccount = OutApp.Session.Accounts.Item(Sheets("Sheet1").Range("B3").Value)
                    
              ' Add recipients, subject, and body
              With OutMail
                  .To = Sheets("Sheet1").Cells(i, 2).Value
                  .CC = Sheets("Sheet1").Cells(i, 3).Value
                  .BCC = Sheets("Sheet1").Cells(i, 4).Value
                  .SendUsingAccount = OutAccount
                  .BodyFormat = 2 ' 2 represents olFormatHTML
      
                  ' Open the Word document
                  Set WordDoc = WordApp.Documents.Open(WordFilePath)
                  
                  ' Find and replace <<Name>> with UserName throughout the document
                  With WordDoc.Content.Find
                      .Text = "<<Name>>"
                      .Replacement.Text = UserName
                      .Wrap = wdFindContinue ' Set this to wdFindContinue if you want to continue searching the entire document
                      .Execute Replace:=wdReplaceAll ' Use wdReplaceOne if you want to replace only the first occurrence
                  End With
                  
                  ' Copy the modified content from Word document
                  WordDoc.Content.Copy
                  
                  ' Clear existing content in the email body
                  .GetInspector.WordEditor.Range.Text = ""
                  
                  ' Paste the modified content into the email body
                  .GetInspector.WordEditor.Range.PasteAndFormat 16 ' 16 represents wdFormatOriginalFormatting
                  
                  ' Close the Word document
                  WordDoc.Close False ' Do not save changes
      
      
                  ' Attachments (if any)
                  If Not IsEmpty(Sheets("Sheet1").Cells(i, 5).Value) Then
                      .Attachments.Add Sheets("Sheet1").Cells(i, 5).Value
                  End If
      
                  .Subject = Subject  ' Set the email subject
                  .Send  ' Send the email
              End With
      
              ' Update the status column
              Sheets("Sheet1").Cells(i, 6).Value = "Sent"
      
              ' Release the email object
              Set OutMail = Nothing
          Next i
      
          ' Release the Outlook application object
          Set OutApp = Nothing
          ' Release the Word application object
          Set WordApp = Nothing
      
          Exit Sub
      
      ErrorHandler:
          MsgBox "An error occurred: " & Err.Description
          Set OutMail = Nothing
          Set OutApp = Nothing
          Set WordApp = Nothing
      End Sub

       

       

       

      • NikolinoDE's avatar
        NikolinoDE
        Gold Contributor

        Rajan1415 

        Your code looks generally well-structured, but it seems there might be an issue with the way you are handling the Outlook references. Specifically, it appears that you are using constants such as olMailItem and wdFindContinue without declaring them explicitly.

        Here is an updated version of your code with proper declarations and some additional comments:

         

        Option Explicit
        
        Sub SendMailViaWord()
            On Error GoTo ErrorHandler
            
            Dim OutApp As Object ' Outlook.Application
            Dim OutMail As Object ' Outlook.MailItem
            Dim OutAccount As Object ' Outlook.Account
            Dim Subject As String
            Dim UserName As String
            Dim WordApp As Object
            Dim WordDoc As Object
            Dim WordFilePath As String
            Dim LastRow As Long
            Dim i As Long
        
            ' Set the Outlook application object
            Set OutApp = CreateObject("Outlook.Application")
            
            ' Set the Word application object
            Set WordApp = CreateObject("Word.Application")
            WordApp.Visible = False
        
            ' Define the mail subject from cell B1
            Subject = Sheets("Sheet1").Range("B1").Value
            
            ' Define the Word file path from cell B2
            WordFilePath = Sheets("Sheet1").Range("B2").Value
        
            ' Find the last row with data in column A (Names)
            LastRow = Sheets("Sheet1").Cells(Sheets("Sheet1").Rows.Count, "A").End(xlUp).Row
        
            ' Loop through the rows starting from row 6 (assuming headers are in row 4)
            For i = 6 To LastRow
                ' Get the username from the Name column (Column A)
                UserName = Sheets("Sheet1").Cells(i, 1).Value
        
                ' Create a new email
                Set OutMail = OutApp.CreateItem(0) ' 0 represents olMailItem
                
                ' Use the account based on the number
                Set OutAccount = OutApp.Session.Accounts.Item(Sheets("Sheet1").Range("B3").Value)
                      
                ' Add recipients, subject, and body
                With OutMail
                    .To = Sheets("Sheet1").Cells(i, 2).Value
                    .CC = Sheets("Sheet1").Cells(i, 3).Value
                    .BCC = Sheets("Sheet1").Cells(i, 4).Value
                    .SendUsingAccount = OutAccount
                    .BodyFormat = 2 ' 2 represents olFormatHTML
        
                    ' Open the Word document
                    Set WordDoc = WordApp.Documents.Open(WordFilePath)
                    
                    ' Find and replace <<Name>> with UserName throughout the document
                    With WordDoc.Content.Find
                        .Text = "<<Name>>"
                        .Replacement.Text = UserName
                        .Wrap = 1 ' 1 represents wdFindContinue
                        .Execute Replace:=2 ' 2 represents wdReplaceAll
                    End With
                    
                    ' Copy the modified content from Word document
                    WordDoc.Content.Copy
                    
                    ' Clear existing content in the email body
                    .GetInspector.WordEditor.Range.Text = ""
                    
                    ' Paste the modified content into the email body
                    .GetInspector.WordEditor.Range.PasteAndFormat 16 ' 16 represents wdFormatOriginalFormatting
                    
                    ' Close the Word document
                    WordDoc.Close False ' Do not save changes
        
                    ' Attachments (if any)
                    If Not IsEmpty(Sheets("Sheet1").Cells(i, 5).Value) Then
                        .Attachments.Add Sheets("Sheet1").Cells(i, 5).Value
                    End If
        
                    .Subject = Subject  ' Set the email subject
                    .Send  ' Send the email
                End With
        
                ' Update the status column
                Sheets("Sheet1").Cells(i, 6).Value = "Sent"
        
                ' Release the email object
                Set OutMail = Nothing
            Next i
        
            ' Release the Outlook application object
            Set OutApp = Nothing
            ' Release the Word application object
            Set WordApp = Nothing
        
            Exit Sub
        
        ErrorHandler:
            MsgBox "An error occurred: " & Err.Description
            Set OutMail = Nothing
            Set OutApp = Nothing
            Set WordApp = Nothing
        End Sub

         

        In this version, I've replaced the constants olMailItem and wdFindContinue with their corresponding numeric values, as constants like these might not be recognized without explicit Outlook or Word references.

        Please make sure to test this code in your environment and adjust it as needed for your specific requirements.

        If this doesn't help, please provide detailed information as provided in the previous night. Operating system, Excel version, storage medium, photos or file (without sensitive data).

Resources