I am trying to slap together a system using Outlook rules and VBA to copy the body of an email message into a plaintext file for further processing, then delete the message from Outlook.
I can't use Outlook rules to delete the message, because I can't control the order in which Outlook executes the actions in the rule. If I could do "Run a script, and then delete" as an action, it would be good enough as-is. However, Outlook will only allow me to delete the message first, and THEN run the script, which is useless to me.
I obviously don't know VBA from a hole in the ground, but from what I've been able to glean from googling, I've got the following VBA which does what I need EXCEPT I can't figure out how to delete the email.
Code so far:
Public Sub SaveBody3(Item As Outlook.MailItem)
Dim olApp As Outlook.Application
Dim olNs As NameSpace
Dim Fldr As MAPIFolder
Dim olMail As MailItem
Dim i As Integer
Dim fso As New FileSystemObject
Dim ts As TextStream
Set olApp = New Outlook.Application
Set olNs = olApp.GetNamespace("MAPI")
Set Fldr = olNs.GetDefaultFolder(olFolderInbox)
i = 1
For Each olMail In Fldr.Items
If InStr(olMail.Subject, "my_very_specific_subject_line") Then
Set ts = fso.OpenTextFile("\\path\to\textfile\filename_" & Format(Now, "yyyymmddhhnnss") & ".txt", ForWriting, True)
ts.Write (olMail.Body)
ts.Close
olMail.Delete 'Shouldn't this delete??
Set ts = Nothing
Set fso = Nothing
i = i + 1
End If
Next olMail
Set Fldr = Nothing
Set olNs = Nothing
Set olApp = Nothing
End Sub
.Deletemethod should delete the msg (and it does when I test a simple case). Do you get an error or anything? - David Zemens