0

This post discusses a VBA solution to replacing text in an incoming email with Outlook rules.

I used the same approach to remove "External Message" text from the top of emails I receive (it's actually 2 lines of text the employer inserts, really annoying). However, when VBA does the replacement, the resulting email also changes formatting of the email. The text is replaced as intended (great!), but all hyperlinks in the email are expanded out and all other html formatting is lost (not good). It looks like it has been converted to plain text. Is there a way to replace text of incoming messages in Outlook without losing HTML formatting?

Here is the code I am running:

Sub RemoveExternalText(MyMail As MailItem)
   Dim body As String, re As Object, match As Variant

   body = MyMail.body
   Set re = CreateObject("vbscript.regexp")
   re.Pattern = "External Message"

   For Each match In re.Execute(body)
       body = Replace(body, match.Value, "")
   Next

   MyMail.body = body
   MyMail.Save

End Sub

1 Answer 1

2

While reading about creating HTML email with VBA, I see they do not use "MyMail.body" but instead use "MyMail.HTMLbody".

Changing the code with that syntax solved the problem!

Sub RemoveExternalText(MyMail As MailItem)
  Dim body As String, re As Object, match As Variant

  body = MyMail.HTMLBody
  Set re = CreateObject("vbscript.regexp")
  re.Pattern = "External Message"

  For Each match In re.Execute(body)
      body = Replace(body, match.Value, "")
  Next

  MyMail.HTMLBody = body
  MyMail.Save

End Sub

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .