VBA - How to insert Horizontal Line in Outlook TaskItem - vba

I want to insert an horizontal line, eg., before a text in a TaskItem body. It is possible to do this using Insert menu and clicking the horizontal line button on symbols group. But, how to code this?
This is what I've tried:
Sub NewTask()
Dim objTask As Outlook.TaskItem
Set objTask = Application.CreateItem(olTaskItem)
With objTask
.Subject = "Example Task"
.Body = ??What to put in here?? & "Example Body"
.Save
End With
Set objTask = Nothing
End Sub
This post show how to reach this for Mails. As far as I know, MailItem have Html body property whereas TaskItem does not have.
Thanks in advance.

Instead, you need to use the TaskItem.RTFBody property which returns or sets a byte array that represents the body of the Microsoft Outlook item in Rich Text Format.
The code for a horizontal line is the following:
\pard \brdrb \brdrs\brdrw10\brsp20 {\fs4\~}\par \pard
To set up the RTF formatting in Outlook you may use the following code:
.BodyFormat = olFormatRichText
.Body = StrConv("your RTF string", vbFromUnicode) 'Convert RTF string to byte array
Be aware, 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.
Note, the MailItem.BodyFormat property allows you to programmatically change the editor that is used for the body of an item.

I was not able to reach the solution through RTFBody. However the Word object model approach, pointed by Eugene Astafiev, helped me to solve the issue.
First of all: Add reference to Word library in VBA Editor, Tools, References
And this is the example sub working:
Sub NewTask()
Dim objTask As Outlook.TaskItem
Dim objInsp As Inspector
Dim objDoc As Word.Document
Dim objSel As Word.Selection
Set objTask = Application.CreateItem(olTaskItem)
Set objInsp = objTask.GetInspector
Set objDoc = objInsp.WordEditor
Set objSel = objDoc.Windows(1).Selection
With objTask
.Subject = "Example Task"
objSel.InsertAfter "Example Body"
objDoc.InlineShapes.AddHorizontalLineStandard
.Display
.Save
End With
Set objTask = Nothing
Set objInsp = Nothing
Set objDoc = Nothing
Set objSel = Nothing
End Sub

Related

I want to add "CC" and Text in the body of this code. What should I do to add it?

I have been able to create an automated email reply as I wanted. However, I wanted to add text in the body of the email and cc to add email address. How should I add it?
Sub FwdSelToAddr()
Dim objOL As Outlook.Application
Dim objItem As Object
Dim objFwd As Outlook.MailItem
Dim strAddr As String
Dim objRecip As Outlook.Recipient
Dim objReply As MailItem
On Error Resume Next
Set objOL = Application
Set objItem = objOL.ActiveExplorer.Selection(1)
If Not objItem Is Nothing Then
strAddr = ParseTextLinePair(objItem.Body, "Email:")
If strAddr <> "" Then
Set objFwd = objItem.Forward
objFwd.To = strAddr
objFwd.Display
Else
MsgBox "Could not extract address from message."
End If
End If
Set objOL = Nothing
Set objItem = Nothing
Set objFwd = Nothing
End Sub
This is what I have done so far. I just want to be able to add CC email address and text in the body in the automated reply.
You need to modify the code a bit by setting the Cc property and the HTMLBody one if you need to modify or update the message body:
If strAddr <> "" Then
Set objFwd = objItem.Forward
objFwd.To = strAddr
objFwd.Cc = "email#address.com"
objFwd.HTMLBody = "<b>Hello world</b>"
objFwd.Display
Else
Be aware, to preserve the message body from the original email you need to insert your content between the opening <body> and closing </body> tags. If you need to add in the beginning of the message paste your additional text right after the opening tag, if you intend to paste it in the end of message - paste right before the closing tag.
Also you may find the Recipients property of the MailItem class helpful. It allows a more convenient way for setting up recipients for the Outlook items. You can read more about that property in the article that I wrote for the technical blog - How To: Fill TO,CC and BCC fields in Outlook programmatically.

Setting the position of an Attachment in a TaskItem does not work in Outlook 2019

I try to create a task from a MailItem using VBA in Outlook 2019.
According to the docu for Attachment.Add:
Position Optional Long: This parameter applies only to email
messages using the Rich Text format: it is the position where the
attachment should be placed within the body text of the message. A
value of 1 for the Position parameter specifies that the attachment
should be positioned at the beginning of the message body. A value 'n'
greater than the number of characters in the body of the email item
specifies that the attachment should be placed at the end. A value of
0 makes the attachment hidden.
However, if I use position 1 (see below), the icon with the link to the original mail will still be at the end of the body instead at beginning. Am I missing something?
Sub CreateTask()
Set olApp = Outlook.Application
Set Msg = olApp.ActiveExplorer.Selection.Item(1)
Dim olTask As TaskItem
Set olTask = olApp.CreateItem(olTaskItem)
With olTask
.Subject = Msg.Subject
.RTFBody = Msg.RTFBody
.Attachments.Add Msg, , 1 ' For some reasone position argument not working :(
'.Save
.Display
End With
End If
There is an Outlook quirk, .Display before editing.
Appears it applies in this situation too.
Option Explicit
Sub CreateTask()
Dim itm As Object
Dim msg As MailItem
Dim olTask As TaskItem
Set itm = ActiveExplorer.Selection.Item(1)
If itm.Class = olMail Then
Set msg = itm
Set olTask = CreateItem(olTaskItem)
With olTask
.subject = msg.subject
.RTFBody = msg.RTFBody
.Display ' <--- Earlier rather than later
.Attachments.Add msg, , 1
End With
End If
End Sub
Use the MailItem.MarkAsTask method which marks a MailItem object as a task and assigns a task interval for the object.

How can I convert a selection of emails from RichText to HTML Format?

Background:
My work location has a default email format of RichText.
Many people are adding images to their emails.
RichText emails with images are much larger than HTML emails with images.
I can manually open, edit, changed format to HTML, and save to greatly reduce the size of the email. The formatting is maintained during conversion.
However, when I use VBA to open the mail item, change the format and save, the email is not converted.
How can I use vba to change a set of Richtext emails into properly formatted html emails, achieving the same results as manually editing and saving using the Ribbon?
Here is my sample code below, and I can see when I run the code that this line:
myMailItem.BodyFormat = olFormatHTML
is not converting in the same way that the Ribbon is converting.
Public Sub myConvertHTML()
Dim mySelectedItems As Selection
Dim myMailItem As MailItem
Dim myRichText As String
Dim myHtmlText As String
' Set reference to the Selection.
Set mySelectedItems = ActiveExplorer.Selection
' Loop through each item in the selection.
For Each myMailItem In mySelectedItems
'if the current format is RichText proceed
If myMailItem.BodyFormat = olFormatRichText Then
myMailItem.Display
'this line does not convert the RichText to Html properly
'it seems to convert the images into an attached file ATT#### that is an ole object
'instead of converting the image and using it in html format
'when using the Ribbon and changing the format to HTML,
'the email is converted and formatting maintained
myMailItem.BodyFormat = olFormatHTML
myMailItem.Save
myMailItem.Close olSave
Else
MsgBox "Already in RichText Format: " & myMailItem.Subject, vbInformation
End If
Next
MsgBox "All Done. Email converted to HTML.", vbOKOnly, "Message"
Set mySelectedItems = Nothing
Set myMailItem = Nothing
End Sub
I tried manipulating the Ribbon from inside VBA, but I have not been able to figure out how to call the Ribbon element
(Format Text/Format/HTML).
Any suggestions are appreciated.
Thanks to Niton here is my working final solution.
Public Sub myConvertHTML002()
'takes selected list of items in Outlook and converts all mailItems that are RichText into HTML Format
Dim mySelectedObjects As Selection
Dim myObject As Object
Dim myMailItem As MailItem
Dim objItem As Object
' Set reference to the Selection.
Set mySelectedObjects = ActiveExplorer.Selection
' Loop through each item in the selection.
For Each myObject In mySelectedObjects
If myObject.Class = olMail Then
Set myMailItem = myObject
'if the current format is RichText proceed
If myMailItem.BodyFormat = olFormatRichText Then
'have to display the email so we can use the command bars
myMailItem.Display
'special code because we can't change the format of the item from within the item
'we have to use the ActiveInspector
On Error Resume Next
Set objItem = ActiveInspector.CurrentItem
On Error GoTo 0
If Not objItem Is Nothing Then
If objItem.Class = olMail Then
ActiveInspector.CommandBars.ExecuteMso ("EditMessage")
ActiveInspector.CommandBars.ExecuteMso ("MessageFormatHtml")
End If
End If
myMailItem.Close olSave
Else
'MsgBox "Already in RichText Format: " & myMailItem.Subject, vbInformation
End If
End If
Next
MsgBox "All Done. Email converted to HTML.", vbOKOnly, "Message"
Set mySelectedItems = Nothing
Set myMailItem = Nothing
End Sub
You can click a button with ExecuteMso.
CommandBars.ExecuteMso Method "Works on controls that are built-in buttons..."
Sub ChangeToHTML()
Dim objItem As Object
Dim objMail As mailitem
On Error Resume Next
Set objItem = ActiveInspector.currentItem
On Error GoTo 0
If Not objItem Is Nothing Then
If objItem.Class = olMail Then
ActiveInspector.CommandBars.ExecuteMso ("MessageFormatHtml")
End If
End If
End Sub
You can see MessageFormatHtml, the IdMso, as the last bit of text when you hover over the selection when adding a built-in button for the Quick Access Toolbar or a ribbon.

Outlook Email created in VBA using a template converts to plain text when saved

Below is the code that I am running in ThisOutlookSession. The code is meant to check all incoming emails and if the email is from a certain email address and contains a specific string in the subject then a new email is created from a template and the triggering email is attached and the email is then sent out to a different email address. This portion all works fine.
Also to note I am using windows 10 and office 2016.
The problem that I am having is the email is converted to plain text unless it is displayed first. The template that I have created is saved as a HTML formatted message. I have tried adding lines such as
NewMsg.BodyFormat = olFormatHTML
NewMsg.save
But this doesn't seem to work as the email that is sent was still in the plain text format. If I add the following to that the message it basically works.
NewMsg.BodyFormat = olFormatRichText
NewMsg.save
NewMsg.BodyFormat = olFormatHTML
NewMsg.save
However the above block of code removes a lot of the formatting that was saved in my template such as different fonts/ font sizes.
Am I missing something about working with templates in VBA?
Also The problem that I am having with displaying the message first is two things. The obvious one is the flash that this causes because the message is briefly displayed. The second is my default signature is also added to the displayed message but I wanted to use a custom signature that I built into my template.
Here is my full code with sensitive information removed.
Private WithEvents Items As Outlook.Items
Private Sub Application_Startup()
Dim olApp As Outlook.Application
Dim objNS As Outlook.NameSpace
Set olApp = Outlook.Application
Set objNS = olApp.GetNamespace("MAPI")
' default local Inbox
Set Items = objNS.GetDefaultFolder(olFolderInbox).Items
End Sub
Private Sub Items_ItemAdd(ByVal item As Object)
On Error GoTo ErrorHandler
Dim Msg As Outlook.MailItem
Dim NewMsg As Outlook.MailItem
If TypeName(item) = "MailItem" Then
Set Msg = item
If Msg.SenderEmailAddress <> "example#example.com" Then GoTo Skip
If InStr(1, Msg.Subject, "Specific String") > 0 Then 'checks if subject contains the proper string
Set NewMsg = Application.CreateItemFromTemplate("Template Path")
Msg.Subject = Replace(Msg.Subject, "Old Subject", "New subject")
Msg.Save
NewMsg.HTMLBody = NewMsg.HTMLBody
NewMsg.Attachments.Add Msg
NewMsg.Recipients.Add("Example#Example.com")
NewMsg.Subject = Msg.Subject
NewMsg.Save
NewMsg.Send
End If
End If
Skip:
ProgramExit:
Exit Sub
ErrorHandler:
MsgBox Err.Number & " - " & Err.Description
End Sub
Reset the HTMLBody property - that will force HTML format:
Msg.HTMLBody = Msg.HTMLBody

Outlook VBA: Using Word Inspector to create a Follow Up Meeting Invite

I am creating a VBA Macro in Outlook that will copy an existing meeting invite and create a follow up meeting invite. It should be fairly easy since I have all the parts to this puzzle.
My problem is with the body of the invite; all formatting and pictures are lost. For this reason, I need to use the Word Inspector object to preserve any special formatting and images. I figured out the code using Word and recording a macro.
So I have figured out the code for copying text using the Word Inspector, but I am not sure on how to paste it in another invite.
Sub copyPaste()
Dim objOL As Outlook.Application
Dim objNS As Outlook.NameSpace
On Error Resume Next
Set objOL = Application
If objOL.ActiveInspector.EditorType = olEditorWord Then
Set objDoc = objOL.ActiveInspector.WordEditor
Set objNS = objOL.Session
Set objSel = objDoc.Windows(1).Selection
objSel.WholeStory
objSel.Copy
objSel.PasteAndFormat (wdFormatOriginalFormatting)
End If
Set objOL = Nothing
Set objNS = Nothing
End Sub
Please see my current Outlook code:
Sub scheduleFollowUpMeeting()
'Declarations
Dim obj As Object
Dim Sel As Outlook.Selection
'Selecting the Email
If TypeOf Application.ActiveWindow Is Outlook.Inspector Then
Set obj = Application.ActiveInspector.currentItem
Else
Set Sel = Application.ActiveExplorer.Selection
If Sel.Count Then
Set obj = Sel(1)
End If
End If
If Not obj Is Nothing Then
MsgBox "The original meeting has been copied." & vbCrLf & "Please kindly update any new details like date/time.", , "Follow Up Meeting - Amit P Shah"
Dim objFollowUp As Outlook.AppointmentItem
Set objFollowUp = Application.CreateItem(olAppointmentItem)
'Copies existing details from original Invite
With objFollowUp
.MeetingStatus = olMeeting
.Subject = "Follow Up: " & obj.Subject
.Body = obj.Body
.Start = Now + 1 'Takes today's date and adds 1 day
.End = DateAdd("n", obj.Duration, .Start)
'Other
.AllDayEvent = obj.AllDayEvent
.BusyStatus = obj.BusyStatus
.Categories = obj.Categories
.Companies = obj.Companies
.ForceUpdateToAllAttendees = obj.ForceUpdateToAllAttendees
.Importance = obj.Importance
.Location = obj.Location
.OptionalAttendees = obj.OptionalAttendees
.ReminderMinutesBeforeStart = obj.ReminderMinutesBeforeStart
.ReminderOverrideDefault = obj.ReminderOverrideDefault
.ReminderPlaySound = obj.ReminderPlaySound
.ReminderSet = obj.ReminderSet
.ReminderSoundFile = obj.ReminderSoundFile
.ReplyTime = obj.ReplyTime
.RequiredAttendees = obj.RequiredAttendees
.Resources = obj.Resources
.ResponseRequested = obj.ResponseRequested
.Sensitivity = obj.Sensitivity
.UnRead = obj.UnRead
.Display
End With
End If
End Sub
Any help would greatly be appreciated. Many thanks in advance!
I'm not a specialist on this subject but i used to work and manipulate Outlook's AppointmentItem in C# and that's how i see the thing.
Actually, if you try to copy the body of a meeting on another meeting, like you said, you will lose all the special formating, images, etc.
The new body will only contain the caracters without format.
I think you can't put formatted text on the body property, you have to use the rtfbody property or like you did when you copy the body of your original appointment, use the WordEditor property in the Inspector object.
So, try to use the WordEditor of the new Item you're creating (like you did to take the original content) and to add content in it.
That's what i had to do for putting formatted text in the body of an AppointmentItem in C#.
I did something like that :
Word.Document myDoc = myItem.GetInspector.WordEditor;
Word.Paragraphs paragraphs = myDoc.Content.Paragraphs;
Word.Paragraph para = paragraphs.Add();
para.Range.Text = yourFormattedTextHere;
After that, you may need to release the variables created, but i'm not sure about that.