How to filter Outlook email using a Rule with a VBA script?

Solution 1:

I looked high and low for all these parts required to make this simple filter happen. Unix procmail filters are so easy to use by comparison. All the Microsoft Outlook wizards get in the way of a simple filter using wildcards. While many email filter conditions Microsoft provides by default are useful nothing can beat the flexibility and customization of running code.

  1. Write your code.

Alt-F11 brings up the VBA code editor. Double click on ThisOutlookSession. Write your code. In my case it's using a regex on the subject line and moving it not to the DefaultFolder but my own pst in a subfolder.

Sub filter(Item As Outlook.MailItem)
    Dim ns As Outlook.NameSpace
    Dim MailDest As Outlook.Folder
    Set ns = Application.GetNamespace("MAPI")
    Set Reg1 = CreateObject("VBScript.RegExp")
    Reg1.Global = True
    Reg1.Pattern = "(.*Abc.20.*)"
    If Reg1.Test(Item.Subject) Then
        Set MailDest = ns.Folders("Personal Folders").Folders("one").Folders("a")
        Item.Move MailDest
    End If
End Sub
  1. Run the code for each incoming email with a Rule.

Under rules select "Manage Rules and Alerts...". The new rule will look like

Apply this rule after the message arrives run Project1.ThisOutlookSession.filter

To get this, for Step 1: Select condition(s): just click next. Confirm it applies to all messages by clicking OK. For Select action(s) check "run a script" then click to choose the filter script and select Next or Finish. For Select exception(s) click Next or Finish. Give it a good name like vba-filter and check Turn on this rule. click Finish. Since it copes to a local folder click OK when it asks to confirm this rule won't work for email you check online or from another device. Click OK to the Rules and Alerts dialog box.

  1. Outlook doesn't like it when macros are not signed. To self-sign your macros create a certificate and use it.