How to Embed a PDF Document in an Email Message - vba

I am trying embed PDF into body of my email .
I tried following code but it keeps opening word but attaches pdf file but does not embed pdf as a object in the body of email. Any help on this will be appreciated.
Public Sub CreateNewMessage()
Dim objMsg As MailItem
Set objMsg = Application.CreateItem(olMailItem)
With objMsg
.To = "test#tst.com"
.Subject = "This is the subject"
.BodyFormat = olFormatHTML
.Attachments.Add ("C:\Work\Dashbaord.pdf"), olOLE 'Attach PDF File
'Embed PDF
Set wordapp = CreateObject("word.Application")
wordapp.Documents.Open FileName:="C:\Work\" & "Dashbaord.pdf"
wordapp.Visible = True
'Embed PDF
wordapp.Visible = True
Set wordapp = GetObject(, "Word.Application")
wordapp.Selection.InlineShapes.AddOLEObject ClassType:="AcroExch.Document.11", _
FileName:="C:\Work\Dashbaord & ".pdf", LinkToFile:=False, _
DisplayAsIcon:=False
.Display
End With
Set objMsg = Nothing
End Sub

Should be something like this.
Public Sub InsetObject()
Dim Inspector As Outlook.Inspector
Dim wdDoc As Word.Document
Dim Selection As Word.Selection
Dim Email As Outlook.mailitem
Set Email = Application.CreateItem(olMailItem)
With Email
.To = "0m3r#Email.com"
.subject = "This is the subject"
.Attachments.Add ("C:\Temp\TempFile.pdf")
.Display
Set Inspector = Application.ActiveInspector()
Set wdDoc = Inspector.WordEditor
Set Selection = wdDoc.Application.Selection
Selection.InlineShapes.AddOLEObject ClassType:="AcroExch.Document.DC", _
FileName:="C:\Temp\TempFile.pdf", _
LinkToFile:=False, DisplayAsIcon:=False
End With
Set Inspector = Nothing
Set wdDoc = Nothing
Set Selection = Nothing
End Sub
InlineShapes.AddOLEObject Method (Word)
Creates an OLE object. Returns the InlineShape object that represents the new OLE object.
InlineShape Object (Word)
Represents an object in the text layer of a document. An inline shape can only be a picture, an OLE object, or an ActiveX control. The InlineShape object is a member of the InlineShapes collection. The InlineShapes collection contains all the shapes that appear inline in a document, range, or selection.
InlineShape objects are treated like characters and are positioned as characters within a line of text.
Reference to Microsoft Word xx.x Object Library

Related

Paste Text in specified position

I have code from searches modified for my need.
I need to position the paste under the "Conditions" text in the xOutMsg variable. It is pasting into the first line in the email.
How do I paste on the next line after the word "Conditions"?
Sub PrepareConditionsEmail()
Dim objDoc As Word.Document
Dim objSel As Word.Selection
Dim xOutApp As Object
Dim xOutMail As Object
Dim xOutMsg As String
On Error Resume Next
Set xOutApp = CreateObject("Outlook.Application")
Set xOutMail = xOutApp.CreateItem(0)
xOutMsg = "<br /><br /><b><u>Conditions:</b></u><br /><br />" & "<b><u> </b></u><br />"
With xOutMail
'.To = "Email Address"
.CC = ""
.BCC = ""
.Subject = "Conditions"
.HTMLBody = xOutMsg
.Display
End With
Set xOutMail = Nothing
Set xOutApp = Nothing
On Error Resume Next
Set objDoc = Application.ActiveInspector.WordEditor
Set objSel = objDoc.Windows(1).Selection
objSel.PasteSpecial Link:=False, _
DataType:=wdPasteText, _
Placement:=wdInLine, _
DisplayAsIcon:=False
End Sub
It seems you need to parse the message and insert your own text or markup there. The MailItem.HTMLBody property sets a string representing the HTML body of the specified item. Use the InStr function which returns a long specifying the position of the first occurrence of one string within another. After you get the keyword position you may insert your substring right after the keyword.
InStr(mail.HTMLBody, "keyword", 1)
Read more about the InStr function in MSDN.
The Outlook object model supports three main ways of customizing the message body:
The Body property returns or sets a string representing the clear-text body of the Outlook item.
The HTMLBody property of the MailItem class returns or sets a string representing the HTML body of the specified item. Setting the HTMLBody property will always update the Body property immediately. For example:
Sub CreateHTMLMail()
'Creates a new e-mail item and modifies its properties.
Dim objMail As Outlook.MailItem
'Create e-mail item
Set objMail = Application.CreateItem(olMailItem)
With objMail
'Set body format to HTML
.BodyFormat = olFormatHTML
.HTMLBody = "<HTML><BODY>Enter the message text here. </BODY></HTML>"
.Display
End With
End Sub
The Word object model can be used for dealing with message bodies. See Chapter 17: Working with Item Bodies for more information.
There is no need to mix HTMLBody and WordEditor approaches together. You can choose a single way and use it.

Insert the contents of a Word Document into an email and include the default signature using VBA

I used the code provided by Patrick Wynne in How to send a Word document as body of an email with VBA, but it overwrites the signature. Is there a way to change the code to leave the default signature in place when pasting the contents of the word document?
Here is the code:
Sub emailFromDoc()
Dim wd As Object, editor As Object
Dim doc As Object
Dim oMail As MailItem
Set wd = CreateObject("Word.Application")
Set doc = wd.documents.Open(...path to your doc...)
doc.Content.Copy
doc.Close
set wd = Nothing
Set oMail = Application.CreateItem(olMailItem)
With oMail
.BodyFormat = olFormatRichText
Set editor = .GetInspector.WordEditor
editor.Content.Paste
.Display
End With
End Sub
You might use:
Sub emailFromDoc()
Dim wd As Object, editor As Object
Dim doc As Object
Dim Rng As Object
Dim oMail As MailItem
Set wd = CreateObject("Word.Application")
Set doc = wd.documents.Open(...path to your doc...)
doc.Content.Copy
doc.Close
Set wd = Nothing
Set oMail = Application.CreateItem(olMailItem)
With oMail
.BodyFormat = olFormatRichText
Set editor = .GetInspector.WordEditor
Set Rng = editor.Content
Rng.Collapse 1
Rng.Paste
.Display
End With
End Sub

VBA to format selected text in Outlook

I want to highlight text in an email and format it to font consolas and indent it once.
I have tried this but get an error:
Sub Code()
Selection.Font.Name = "Consolas"
Selection.Paragraphs.Indent
End Sub
Run-time error '429':
ActiveX component can't create object
You can use WordEditor to edit selected text in mail:
Private Sub Code()
' Mail must be in edit mode - compose, reply, forward
' If reading mail then under Actions | Edit Message
' Select some text
Dim objDoc As Object
Dim objSel As Object
Set objDoc = ActiveInspector.WordEditor
Set objSel = objDoc.Windows(1).Selection
objSel.Font.name = "Consolas"
objSel.Paragraphs.Indent
End Sub
Code with validations:
Sub FormatSelection()
' With extra validation for troubleshooting
' Code in Outlook
' Mail must be in edit mode - compose, reply, forward
' If reading mail then under Actions | Edit Message
' Select some text
Dim myInspector As Inspector
Dim myObject As Object
Dim myItem As mailItem
Dim myDoc As Word.Document
Dim mySelection As Word.Selection
Set myInspector = ActiveInspector
If myInspector Is Nothing Then
MsgBox "No inspector. Open a mailitem and select some text."
GoTo ExitRoutine
End If
If myInspector.EditorType <> olEditorWord Then
'https://msdn.microsoft.com/en-us/vba/outlook-vba/articles/oleditortype-enumeration-outlook
' olEditorWord / 4 / Microsoft Office Word editor
Debug.Print "EditorType: " & myInspector.EditorType
MsgBox "Editor is not Microsoft Office Word editor"
GoTo ExitRoutine
End If
' Probably not needed. EditorType should be enough
'If myInspector.IsWordMail = False Then
' MsgBox "myInspector.IsWordMail = False"
' GoTo ExitRoutine
'End If
On Error Resume Next
Set myObject = myInspector.currentItem
On Error GoTo 0
If myObject Is Nothing Then
MsgBox "Open a mailitem and select some text."
GoTo ExitRoutine
End If
If myObject.MessageClass = "IPM.Note" Then
'Should be equivalent to If myObject.Class = olMail Then
Set myItem = myObject
Set myDoc = myInspector.WordEditor
Set mySelection = myDoc.Application.Selection
Debug.Print "Selected text is: " & mySelection
MsgBox "Selected text is: " & vbCr & vbCr & mySelection
mySelection.Font.name = "Consolas"
mySelection.Paragraphs.Indent
Else
MsgBox "Not a mailitem. Open a mailitem and select some text."
GoTo ExitRoutine
End If
ExitRoutine:
Set myInspector = Nothing
Set myObject = Nothing
Set myItem = Nothing
Set myDoc = Nothing
Set mySelection = Nothing
End Sub
Looks like you are trying to mix the Word object model with Outlook. The Selection class in Outlook is not the same as the Selection class from the Word object model. Moreover, there is no such shortcuts in Outlook. You must retrieve it each time you need it.
The Outlook object model provides three main ways for working with item bodies:
The Body property. A raw text.
The HTMLBody property. The body is represented by the html markup.
The Word object model. The WordEditor property of the Inspector class returns and instance of the Word Document class which represents the body.
You can read more about this in the Chapter 17: Working with Item Bodies article in MSDN. It describes all these properties in depth.

How to send a Word document as body of an email with VBA

I've created a macro that works with outlook and excel that will use a list of email addresses (in excel) and send all those addresses an email (in outlook). I want to take a word document (from microsoft word) and use it as the body of the email. The problem is, I will have images in the word document and I need the word document to keep it's formatting. Right now, my VBA takes the content of my word document but the formatting is gone and images aren't included. This is my code:
Sub spamEmail()
'Setting up the Excel variables.
Dim olApp As Object
Dim oMail As Outlook.MailItem
Dim iCounter As Integer
Dim Dest As Variant
Dim SDest As String
Dim Excel As Object
Dim Name As String
Dim Word As Object
Dim oAccount As Outlook.Account
Dim doc As Word.Document
Dim itm As Object
Dim MsgTxt As String
'Set the outlook account to send.
Set oAccount = Application.Session.Accounts.Item(2)
'Create excel object.
Set Excel = CreateObject("excel.application")
Excel.Visible = True
Excel.Workbooks.Open ("C:\Users\Deryl Lam\Documents\Book1.xlsx")
Excel.Workbooks("Book1.xlsx").Activate
'Create a word object.
Set Word = CreateObject("word.application")
Set doc = Word.Documents.Open _
(FileName:="C:\Users\Deryl Lam\Documents\emailBody.docx", ReadOnly:=True)
'Pulls text from file for message body
MsgTxt = doc.Range(Start:=doc.Paragraphs(1).Range.Start, _
End:=doc.Paragraphs(doc.Paragraphs.Count).Range.End)
'Loop through the excel worksheet.
For iCounter = 1 To WorksheetFunction.CountA(Workbooks("Book1.xlsx").Sheets(1).Columns(1))
'Create an email for each entry in the worksheet.
Set oMail = Application.CreateItem(olMailItem)
With oMail
SDest = Cells(iCounter, 1).Value
If SDest = "" Then
'Dont do anything if the entry is blank.
Else
'Do additional formatting on the BCC and Subject lines, add the body text from the spreadsheet, and send.
Name = Cells(iCounter, 2).Value
.BCC = SDest
.Subject = "FYI"
.Body = "Dear " & Name & "," & vbCrLf & MsgTxt
'SendUsingAccount is new in Office 2007
'Change Item(1)to the account number that you want to use
.SendUsingAccount = oAccount
.Send
End If
End With
Next iCounter
'Clean up the Outlook application.
Set olMailItm = Nothing
Set olApp = Nothing
End Sub
I've searched all over google for a solution but I haven't found one. How can I send a word document as the body of the email with it's formatting in tact and the images included?
You are getting the contents of your template document as a string, which by definition will not contain any formatting or images. You should instead copy the contents to the clipboard and then paste them into the new email.
Something like this:
Sub emailFromDoc()
Dim wd As Object, editor As Object
Dim doc As Object
Dim oMail As MailItem
Set wd = CreateObject("Word.Application")
Set doc = wd.documents.Open(...path to your doc...)
doc.Content.Copy
doc.Close
set wd = Nothing
Set oMail = Application.CreateItem(olMailItem)
With oMail
.BodyFormat = olFormatRichText
Set editor = .GetInspector.WordEditor
editor.Content.Paste
.Display
End With
End Sub
If not for the images, you could save the document as an HTML file, read its contents, then set the MailItem.HTMLBody property.
Images are more involved. I don't see a straightforward way to bring them into a message body.

Programmatically change font properties in email body

I have been successfully programming this in PowerPoint VBA but haven't been able to make it work on Outlook.
I have an email ready to be sent in Outlook 2013
I want to scan the body of the email for bold text (i.e., bold characters) and change its color to red
(nice to have) Exclude from the macro the signature
I tried several attempts with "Substitute", "if"-loop but no success. Thanks a lot for putting me on the right track.
The following code converts the color of the body but does not discriminate for bold words. Any ideas?
Public Sub FormatSelectedText()
Dim objItem As Object
Dim objInsp As Outlook.Inspector
' Add reference to Word library
' in VBA Editor, Tools, References
Dim objWord As Word.Application
Dim objDoc As Word.Document
Dim objSel As Word.Selection
On Error Resume Next
'Reference the current Outlook item
Set objItem = Application.ActiveInspector.CurrentItem
If Not objItem Is Nothing Then
If objItem.Class = olMail Then
Set objInsp = objItem.GetInspector
If objInsp.EditorType = olEditorWord Then
Set objDoc = objInsp.WordEditor
Set objWord = objDoc.Application
Set objSel = objWord.Selection
' replace the With block with your code
With objSel
' Formatting code goes here
'.Font.Size = 18
If .Font.Bold = True Then
.Font.Color = wdColorBlue
End If
.Font.Color = wdColorRed
'.Font.Italic = True
'.Font.Name = "Arial"
End With
End If
End If
End If
Set objItem = Nothing
Set objWord = Nothing
Set objSel = Nothing
Set objInsp = Nothing
End Sub
First of all, I'd suggest starting from the Getting Started with VBA in Outlook 2010 article in MSDN.
You can use the HTMLBody property of Outlook items to get the HTML content of the message body or use the Word object model to get the job done. The WordEditor property of the Inspector class returns an instance of the Document class from the WOM (Word object model). See Chapter 17: Working with Item Bodies for more information.