Reputation: 23
I'm trying to save an attachment using Outlook rules and rename it to a word found in the email message body.
The word is on the third populated line, after the colon.
I have a rule set to run this script.
Public Sub saveAttachtoNet(itm As Outlook.MailItem)
Dim objAtt As Outlook.Attachment
Dim saveFolder As String
saveFolder = "O:\EUROMKTG\Marketing Analytics Dept\Campaign
Reporting\Campaign Dashboard\1. Exact Target (Salesforce Mrktg Cloud)"
For Each objAtt In itm.Attachments
objAtt.SaveAsFile saveFolder & "\" & objAtt.DisplayName
Set objAtt = Nothing
Next
End Sub
Upvotes: 2
Views: 1191
Reputation: 14537
I'd do it like this :
Public Sub saveAttachtoNet(itm As Outlook.MailItem)
Dim objAtt As Outlook.Attachment
Dim saveFolder As String
saveFolder = "O:\EUROMKTG\Marketing Analytics Dept" & _
"\Campaign Reporting\Campaign Dashboard" & _
"\1. Exact Target (Salesforce Mrktg Cloud)"
Dim JobTxtInMail As String
JobTxtInMail = "Exported for - JobID:"
Dim StrStart As Integer
StrStart = InStr(1, _
itm.Body, _
JobTxtInMail, _
vbTextCompare) + Len(JobTxtInMail) + 1
Dim JobNum As String
JobNum = Trim(Mid(itm.Body, _
StrStart, _
InStr(StrStart + 1, itm.Body, Chr(13)) - StrStart - 1))
For Each objAtt In itm.Attachments
objAtt.SaveAsFile saveFolder & "\" & JobNum & "__" & objAtt.DisplayName
Set objAtt = Nothing
Next objAtt
End Sub
You may have to tweak a bit the + 1
and - 1
, respectively in StrStart
and JobNum
.
And to change the objAtt.SaveAsFile
to fit the desired output!
Upvotes: 1
Reputation: 12279
It's tricky to do without seeing some example emails but before you launch the For Each objAtt..
loop you want to 'grab' the word. I'd be looking in itm.Body
. If you use Split
to break this up with Chr(13) - a carriage return you then just need to pick the 3rd 'populated' segment. You need confidence that the 3rd line is going to contain a valid filename etc. but see below for an untested idea how you might do it:
Public Sub saveAttachtoNet(itm As Outlook.MailItem)
Dim objAtt As Outlook.Attachment
Dim saveFolder As String
Dim bodystring, sgmnt As String
Dim sgmntcounter As Integer
saveFolder = "O:\EUROMKTG\Marketing Analytics Dept\Campaign " _
& "Reporting\Campaign Dashboard\1. Exact Target (Salesforce Mrktg Cloud)"
bodystring = itm.Body
bodysegments = Split(bodystring, Chr(13))
For Each sgmnt In bodysegments
If sgmnt <> "" Then sgmntcounter = sgmntcounter + 1
If sgmntcounter = 3 Then Exit For
Next
For Each objAtt In itm.Attachments
objAtt.SaveAsFile saveFolder & "\" & sgmnt
Set objAtt = Nothing
Next
End Sub
Upvotes: 1