Forum Discussion
Using word Template as outlook mail body
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
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.
- Rajan1415Jan 24, 2024Copper Contributor
The new code isn't working properly, and I'm getting an error. I'm using Microsoft 365 Enterprise with Windows 11.
The problem is with the ".Send" part of the code. When I change it to ".Display," it opens the preview window just fine. This issue is happening for the first time as I try to use Word as an email template. Everything works fine when I manually include the message in the code.
- NikolinoDEJan 24, 2024Gold Contributor
hmm…The issue seems to be related to the way the Word document is being used as an email template. When you change the code to ".Display" instead of ".Send," it successfully previews the email because the Word content is directly embedded in the email body. However, when you try to send the email using ".Send," there might be a conflict between the Word document and the Outlook mail item, preventing the proper formatting and sending of the email.
To resolve this issue, you can consider the following approaches:
- Separate Word Document and Email: Instead of embedding the Word document directly into the email, you can save the Word document as an HTML file and then attach it to the email. This will ensure that the Word content is properly formatted and handled by Outlook without any conflicts.
- Create Custom Template in Outlook: Consider creating a custom email template in Outlook that uses the desired Word document as a starting point. This template can be linked to the Word document and will allow you to dynamically insert personalized content without embedding the entire document.
- Utilize Third-Party Tools: If you need more advanced functionality or control over the email creation process, you can explore third-party tools that specialize in generating personalized emails from Word templates. These tools often provide more robust integration between Word and Outlook, ensuring seamless email creation and sending.
By implementing one of these approaches, you can effectively use Word documents as email templates and avoid the error associated with directly embedding the Word content into the Outlook mail item. The text and steps were edited with the help of AI.
As a final thought or attempt without being sure if this will work, Let's try a slightly different approach to handle the Word editor in Outlook. Replace the relevant part of your code with the following:
Code:
' ... With OutMail ' ... (previous code remains unchanged) ' Paste the modified content into the email body .GetInspector.WordEditor.Range.PasteSpecial Link:=False, DataType:=wdPasteHTML, Placement:=wdInLine, DisplayAsIcon:=False ' 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 ' ...
In this modification, I replaced the .GetInspector.WordEditor.Range.PasteAndFormat with .GetInspector.WordEditor.Range.PasteSpecial. The PasteSpecial method allows for more control over the pasting process.
Also, please make sure that you have the following line at the beginning of your module to ensure that the Word constants are recognized:
Code:
Const wdPasteHTML As Integer = 10 ' Use the actual value of wdPasteHTML Const wdInLine As Integer = 0 ' Use the actual value of wdInLine Const wdFormatOriginalFormatting As Integer = 16 ' Use the actual value of wdFormatOriginalFormatting
Make sure that the constant values are correctly set according to the version of Word you are using.
After making these changes, try running the code again with the .Send method. If the issue persists, you may consider using the .Display method for now, as it allows you to manually review and send the emails. Alternatively, you might explore other methods like creating the email body directly in VBA without using Word as a template. I'm starting to be unsure whether this can be done with Word document using as a mail template. I can't help any further, I'm at my wits' end.