0
votes

I have a rule in Outlook which sends a daily email into a particular folder. I then have a VBA script which upon noticing a new unread message in that folder goes in and saves the attachment to a folder on my hard drive and does a few other formatting type things (on the attachment).

I then just linked up the script to the rule in the Outlook rules wizard so it runs as a package.

The problem is as follows: the script is kicked off BEFORE the message is sorted into the appropriate folder. In reality it should run after the message is sorted (otherwise there is nothing for it to act upon). Any ideas on how to rectify?

The code currently begins as follows:

    sub saveattachment()

Should it be this instead?

    private sub saveattachment()

or

    public sub saveattachment()

Would it be better to have the "rule" embedded in the macro instead and then just run it as a private sub anytime the daily email appears in my Inbox?

1

1 Answers

0
votes

If you need to assign a VBA macro sub to the Outlook rule, the VBA sub should look like the following one:

Public Sub Test(mail as MailItem)
  ' your code goes there
End Sub

An instance of the MailItem class is passed as a parameter and stands for the email arrived to the Inbox.

But in case if you need to be sure that your code is triggered when a mail is moved to a particular folder you need to handle the ItemAdd event of the Items class which comes from that folder. Be aware, the event is not fired when more than 16 items are added to the folder simultaneously.

Public WithEvents myOlItems As Outlook.Items 

Public Sub Initialize_handler() 
 Set myOlItems = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderContacts).Items 
End Sub 

Private Sub myOlItems_ItemAdd(ByVal Item As Object) 
 Dim myOlMItem As Outlook.MailItem 
 Dim myOlAtts As Outlook.Attachments 
 Set myOlMItem = myOlApp.CreateItem(olMailItem) 
 myOlMItem.Save 
 Set myOlAtts = myOlMItem.Attachments 
 ' Add new contact to attachments in mail message 
 myOlAtts.Add Item, olByValue 
 myOlMItem.To = "Sales Team" 
 myOlMItem.Subject = "New contact" 
 myOlMItem.Send 
End Sub

Finally, you may find the Getting Started with VBA in Outlook 2010 article helpful.