vbaoutlookoutlook-2010outlook-2013

Find Text in an email and delete all text before this in Outlook 2013


I would like to find a string in an email, and delete all text before it. It is much the opposite of this:

    Option Explicit

Sub DeleteAfterText()

' Deletes all text after endStr.

Dim currMail As mailitem
Dim msgStr As String

Dim endStr As String
Dim endStrStart As Long
Dim endStrLen As Long

Set currMail = ActiveInspector.CurrentItem
endStr = "Text"
endStrLen = Len(endStr)

msgStr = currMail.HTMLBody
endStrStart = InStr(msgStr, endStr)

If endStrStart > 0 Then
    currMail.HTMLBody = Left(msgStr, endStrStart + endStrLen)
End If

End Sub

Example taken from this stack overflow page: Find Text in an email and delete all text after this in Outlook 2010

Thanks for your help.


Solution

  • The key line would be something like this:

    currMail.body = Right(msgStr, Len(msgStr) - (endStrStart - 1))
    

    Adding a bit more to the original code:

    Option Explicit
    
    Sub DeleteBeforeText_not_olFormatHTML()
    
    Dim currMail As mailItem
    Dim msgStr As String
    
    Dim endStr As String
    Dim endStrStart As Long
    Dim endStrLen As Long
    
    Set currMail = ActiveInspector.currentItem
    endStr = "Text"
    endStrLen = Len(endStr)
    
    If currMail.BodyFormat = olFormatHTML Then
        currMail.BodyFormat = olFormatRichText
    End If
    
    msgStr = currMail.body
    endStrStart = InStr(msgStr, endStr)
    
    If endStrStart > 0 Then
        currMail.body = Right(msgStr, Len(msgStr) - (endStrStart - 1))
    End If
    
    End Sub