PDA

View Full Version : Moving an email to a new folder, and changing the subject



ukdane
12-11-2009, 07:59 AM
Hi,
I need some code that will help me do the following.
When an email arrives in a folder "x" (not the inbox, as there is already some code in place that will move the email to a different folder "x" ) if the email has an attachment, it needs to be COPIED to a different folder. The subject of the email also has to be changed to some text that can be found within the message body. The text to be used is always the first 10 characters after the text "Consignment NO: " (with a space at the end).

Thanks for your help.

JP2112
12-14-2009, 09:20 AM
Outlook version?

If 2003 (adapted from Stock Event Code (http://www.codeforexcelandoutlook.com/outlook-vba/stock-event-code/)):

Private WithEvents Items As Outlook.Items
Private Sub Application_Startup()
Dim olApp As Outlook.Application
Dim objNS As Outlook.NameSpace
Set olApp = Outlook.Application
Set objNS = olApp.GetNamespace("MAPI")
' (1) default Inbox
Set Items = objNS.GetDefaultFolder(olFolderInbox).Items
End Sub
Private Sub Items_ItemAdd(ByVal item As Object)
On Error Goto ErrorHandler

Dim Msg As Outlook.MailItem
Dim updatedSubject As String
Dim targetMsg As Outlook.MailItem
Dim targetFolder As Outlook.MAPIFolder

If TypeName(item) = "MailItem" Then
Set Msg = item

'(2) where is the message copied?
Set targetFolder = Your Folder

' copy messages with attachments to another folder
If Msg.Attachments.Count > 0 Then
Set targetMsg = Msg.Copy

' (3) update subject with body text
updatedSubject = Mid$(Msg.Body, Instr(Msg.Body, "Consignment NO: ") + 17, 10) & Msg.Subject

With targetMsg
.Subject = updatedSubject
.Save
.Move targetFolder
End With
End If
End If
ProgramExit:
Exit Sub
ErrorHandler:
MsgBox Err.Number & " - " & Err.Description
Resume ProgramExit
End Sub

Place the above code in the ThisOutlookSession module of your Outlook VB IDE. If you already have code, you'll need to integrate this into the existing VBA code. You'll need to edit it in the three spots indicated above.

(1) should point to the folder where the messages ultimately arrive.
(2) targetFolder should point to the destination folder where you want the messages to go.
(3) I'm always a bit shaky with Mid and Instr, you'll need to test and tweak to make sure it's correct.




Hi,
I need some code that will help me do the following.
When an email arrives in a folder "x" (not the inbox, as there is already some code in place that will move the email to a different folder "x" ) if the email has an attachment, it needs to be COPIED to a different folder. The subject of the email also has to be changed to some text that can be found within the message body. The text to be used is always the first 10 characters after the text "Consignment NO: " (with a space at the end).

Thanks for your help.