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.
Related
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.
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
I am trying to write a VBA code in Excel that will create an Outlook message which contains:
text in the body
a table
a signature at the bottom.
Below is a code that I wrote. It was working until I added the Excel Table object to the body of the message. It's coming up with an error message that says:
Run-time error: error type 13, Type Mismatch".
Can someone help with my code below?
Sub send()
Dim OApp As Object, OMail As Object, signature As String
Dim TOEMAIL As Range
Dim CCMEMAIL As Range
Dim SUBJECT As Range
Dim Workbook As Range
Dim Table As Range
Set TOEMAIL = Sheets("Macro").Range("D6")
Set CCEMAIL = Sheets("Macro").Range("D7")
Set SUBJECT = Sheets("Macro").Range("D8")
Set Workbook = Sheets("Macro").Range("D5")
Set Table = Sheets("Sheet1").Range("B7:B17")
Set OApp = CreateObject("Outlook.Application")
Set OMail = OApp.CreateItem(0)
With OMail
.Display
End With
signature = OMail.body
With OMail
.To = TOEMAIL
.CC = CCEMAIL
.SUBJECT = SUBJECT
.Attachments.Add (Workbook)
.body = "Hello, this is a test." & vbNewLine & Table & vbNewLine & signature & vbNewLine
End With
Set OMail = Nothing
Set OApp = Nothing
End Sub
MailItem.Body property expects a string. You are trying to concatenate a few strings and a Range object. It is your responsibility to extract the relevant data from that table and represent it as a string.
You would probably be better off creating an HTML table and setting the MailItem.HTMLBody property instead.
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.
I'm working with Excel's VBA trying to automate the sending of some emails. Right now, the code creates an email based on the cells next to the button clicked, forwards the email to the listed in a cell, and then inserts a specific body message based on some more cells. What is in the cells isn't really important, but what I need to do is search the original forwarded message for specific text, and if found, it needs to highlight that text.
My code is as follows:
Sub Asset_email()
Dim olApp As Outlook.Application
Dim olNs As Namespace
Dim Fldr As MAPIFolder
Dim olMail As Outlook.MailItem
Dim i As Integer
Dim olMsg As Outlook.MailItem
Dim r As Range
Dim strLocation As String
Dim o As Outlook.Application
Dim strbody As String
'Dim olAtt As Outlook.Attachments
'Set olAtt = olMsg.Attachments
Set r = ActiveSheet.Buttons(Application.Caller).TopLeftCell
Range(Cells(r.Row, r.Column), Cells(r.Row, r.Column)).Select
Set olApp = New Outlook.Application
Set olNs = olApp.GetNamespace("MAPI")
Set Fldr = olNs.GetDefaultFolder(olFolderInbox).Folders("Asset Notifications Macro")
i = 1
For Each olMail In Fldr.Items
If InStr(olMail.body, ActiveCell.Offset(rowOffset:=0, ColumnOffset:=-3).Value) <> 0 Then
olMail.display
strbody = "<BODY style=font-size:11pt;font-family:Calibri>Team,<br><br>" & _
"Please see the notice below regarding " & _
ActiveCell.Offset(rowOffset:=0, ColumnOffset:=-2).Value & _
".<br><br> Feel free to email the CSG team at myemailhere#email.com with any questions.<br><br>" & _
"Thank you!"
With olMail.Forward
.To = ActiveCell.Offset(ColumnOffset:=-1)
.display
SendKeys ("%")
SendKeys ("7")
'Call Sleep
Application.Wait (Now + TimeValue("0:00:03"))
.HTMLBody = strbody & "<br>" & .HTMLBody
End With
End If
Next
End Sub
The code works 100%. I just don't know the correct syntax to search and highlight the results.
In the above example, lets say I wanted to find and highlight the words "Thank you". How would one go about this?
You basically have to use the Word Object Model for the text searching and highlighting. There's a perfect example of how to do it in this article: https://msdn.microsoft.com/en-us/library/gg193974.aspx
Highlight in the active Inspector? Try the following.
You can substitute the line set objInspector = Application.ActiveInspector with set objInspector = olMail.GetInspector
wdColorYellow = 65535
set objInspector = Application.ActiveInspector
set objDoc = objInspector.WordEditor
set objFind = objDoc.Content.Find
objFind.HitHighlight "text_to_highlight", wdColorYellow, , false, true
The Outlook object model provides three main ways for working item bodies:
Body - a string representing the clear-text body of the Outlook item.
HTMLBody - a string representing the HTML body of the specified item. In that case you need to parse the HTML markup and add surrounding tags for highlighting the text. For example, you may use the <b> for bold symbols.
Word editor - the Microsoft Word Document Object Model of the message being displayed. The WordEditor property of the Inspector class returns an instance of the Document class from the Word object model which you can use to work on the message body. The Bold property of the Font class allows to format the text as bold.
You can read more about all these ways in the Chapter 17: Working with Item Bodies. It us up to you which way (HTML or Word object model) is to choose for highlighting the text.
Figured it out:
.HTMLBody = Replace(.HTMLBody, "Thank you", "<FONT style=" & Chr(34) & "BACKGROUND-COLOR: yellow" & Chr(34) & ">" & "Thank you" & "</FONT>")