Home > other >  Excel VBA - How to update ReplyAll.HTMLBody while maintaining the original value
Excel VBA - How to update ReplyAll.HTMLBody while maintaining the original value

Time:09-26

I'm having trouble trying to update mailItem.ReplyAll.HTMLBody. I can't seem to add new text to the body without deleting the previous value. The following code below results in an email item that only has the previous HTMLBody in it and not the new "Hello world" text.

mMail.BodyFormat = olFormatHTML
On Error Resume Next
With mMail.ReplyAll
        .HTMLBody = "Hello world" & .HTMLBody
        .Display
End With
On Error GoTo 0

How do I add to the HTMLBody of a ReplyAll email while maintaining the original HTMLBody?

CodePudding user response:

First of all, keep in mind that in case of the HTMLBody property you deal with a HTML web page, so the HTML formatting should be well-formed.

Second, try to split the new item after calling the ReplyAll method which creates a reply to all original recipients from the original message and a new MailItem object that represents the reply is returned.

Dim reply as Outlook.MailItem

On Error Resume Next

Set reply = mMail.ReplyAll
With reply
        .HTMLBody = "<b>Hello world<b>"
        .Display
End With

If you need to insert any text into message body represented by the HTML document, you need to find the opening <body> tag and insert your text right after it instead.

CodePudding user response:

The original code should be sufficient unless missing parts have an impact.

Try moving .Display so HtmlBody is seen before editing.

Option Explicit

Private Sub testActiveInspector()

Dim currItem As Object
Dim replyMail As MailItem

Set currItem = ActiveInspector.CurrentItem

If currItem.Class = olMail Then
    
    currItem.BodyFormat = olFormatHTML
    
    Set replyMail = currItem.ReplyAll
    
    With replyMail
        .Display
        .HtmlBody = "Hello world" & .HtmlBody
    End With

End If

End Sub


Private Sub testSelection()

Dim currItem As Object
Dim replyMail As MailItem

Set currItem = ActiveExplorer.Selection(1)

If currItem.Class = olMail Then
    
    currItem.BodyFormat = olFormatHTML
    
    Set replyMail = currItem.ReplyAll
    
    With replyMail
        .Display
        .HtmlBody = "Hello world" & .HtmlBody
    End With

End If

End Sub

You should remove On Error Resume Next when it is followed by code to create mail. Address any errors appropriately.

You should remove On Error Resume Next in 99.9999% of all other cases.

  • Related