1

I am trying to change incoming emails subject line to only the last 11 characters of the subject line. When I use Item.Subject = Right(Item.Subject,11) it does not work.

Can someone assist?

Full code.

Sub ChangeSubjectForward(Item As Outlook.MailItem)
Item.Subject = Right(Item.Subject, 11) 
Item.Save
End Sub
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343

2 Answers2

0

I found another SO thread that says you can't modify the subject of a message without opening it first. We can use ActiveInspector to get a handle on the Item after we display it. Then we can change it, save it, and close it. I added a check to see if the subject is actually longer than 11 characters before we attempt to truncate it.

Try this:

Public Sub ChangeSubjectForward(ByRef Item As Outlook.MailItem)
    Debug.Print Now                              '  This shows you when the code runs
    If Len(Item.Subject) > 11 Then
        Debug.Print "Subject is too long. Trimming..." '  This shows that we tried to truncate.

        Item.Display                             'Force the pop-up

        Dim thisInspector As Inspector
        Set thisInspector = Application.ActiveInspector

        Set Item = thisInspector.CurrentItem     ' Get the handle from the Inspector
        Item.Subject = Right$(Item.Subject, 11)
        Item.Save
        Item.Close
    End If
End Sub
HackSlash
  • 4,944
  • 2
  • 18
  • 44
  • I wish I understood all of that. I am decently new to VBA and I have never used it in Outlook. That still does not work. Could it be the way my rule is set up? Could that prevent it? – sbradley4554 Dec 19 '18 at 21:34
  • Sorry, I added explanations. I also added some debug lines so you can see when your code ran. Just open the "Immediate Window" `CTRL+G` and you will see the debug messages when the code runs. – HackSlash Dec 20 '18 at 17:47
  • Thank you so much. That is awesome info. – sbradley4554 Dec 20 '18 at 17:48
  • Absolutely not - to change any property, displaying the item is not necessary. As long as you call Save. – Dmitry Streblechenko Dec 20 '18 at 20:24
  • @HackSlash - This is getting closer! The email opens, subject changes, but the window does not close. Also, the Subject in the Reading Pane does not change. For the window now closing, could I add `MailItem.Close` after `Item.Save`? – sbradley4554 Dec 20 '18 at 20:55
  • I added `Item.Close`. Try that. – HackSlash Dec 20 '18 at 21:49
0

You could create a macro rule then run the below code:

Sub save_to_dir_test1(mymail As MailItem)
Dim strID As String
Dim objMail As Outlook.MailItem

strID = mymail.EntryID
Set objMail = Application.Session.GetItemFromID(strID)
objMail.Subject = Right(m.Subject, 11)
objMail.Save
Set objMail = Nothing
End Sub

For more information, please refer to this link:

Run a Script Rule: Change Subject then Forward Message

Getting the incoming email in outlook via VBA

Alina Li
  • 884
  • 1
  • 6
  • 5