VBA Script to Dynamically Change Subject Line on Incoming Emails for Outlook 2013

2

1

I have looked at this Outlook script example, which is similar and a great start for me: Outlook Script to edit subject

However, I am in need to change incoming message subject lines on arrival in a more difficult method which requires more complex string manipulation.

This is actually my base code I've used, which worked up to date:

Sub ConvertToPlain(MyMail As MailItem)
    Dim strID As String
    Dim objMail As Outlook.MailItem

    strID = MyMail.EntryID
    Set objMail = Application.Session.GetItemFromID(strID)
    objMail.Subject = Left(objMail.Subject, 18)
    objMail.Save

    Set objMail = Nothing
End Sub

Now, I the original subjects are always in the following format (anything in brackets is a variable):

Ticket [#] - [SOMETHING] - [SOMETHING] - [TITLE]

I wish to remove the "[SOMETHING] - [SOMETHING] -" which is dynamically changing as you can see, and keep only:

Ticket [#] - [TITLE]

In this way, I can once again sort/filter with ease in outlook. How can this be accomplished in VBA? Thank you.

Shackrock

Posted 2015-12-21T13:30:08.373

Reputation: 580

Answers

3

Your best bet is either to REGEX out the parts you want, or if you know the format is ALWAYS in this format, you could split the string on the - and take the first and last ones.

Along the lines of:

Sub ConvertToPlain(MyMail As MailItem)
    Dim strID As String
    Dim objMail As Outlook.MailItem
    Dim splitSubject() as String
    Dim concatSubject as String

    strID = MyMail.EntryID
    Set objMail = Application.Session.GetItemFromID(strID)
    splitSubject = Split(objMail.Subject, "-")
    concatSubject = splitSubject(LBound(splitSubject)) & " - " & splitSubject(UBound(splitSubject))
    objMail.Subject = concatSubject
    objMail.Save

    Set objMail = Nothing
End Sub

That code is completely untested but hopefully puts you on track somewhat.

Jonno

Posted 2015-12-21T13:30:08.373

Reputation: 18 756

Did a few test cases, and so far so good! The split function is wonderful here! So the LBound picks up the first "before the dash" and the UBound picks up the last "after the dash" ? How would I access the middle sections between the dashes if desired in the future? Thanks! – Shackrock – 2015-12-21T14:15:51.863

The LBound and UBound return the first and last indexes of the array. To access other parts, use

splitSubject(0) splitSubject(1) splitSubject(2) etc – Jonno – 2015-12-21T14:17:11.023