Outlook – Make Outlook run rules on non-inbox folders automatically

gmailimapmicrosoft-outlookrules

I currently have my Outlook setup with Gmail. I have a couple of rules that I have defined which run on different folders (lables) in my account. I have filters already setup in GMail which will make emails skip the inbox and put them in the respective folders.

Whenever I get a new email, in those folders, my rules are not run (they are just for setting categories). I have to run them manually. I think its because the emails don't come to the inbox first but directly into the folder. Is there anyway to make outlook run rules automatically on those folders? A scheduled run should also be fine.

Best Answer

Here it is. Note this is specific to the Junk folder (olFolderJunk is an Outlook constant), and it will run any filter I create prefixed with "JUNK_FILTER_".

It is optimistic and has virtually no error checking, so use it at your peril. Don't use it if you don't understand it :)

Sub runRulesOnJunkFolder()
    Dim st As Outlook.Store
    Dim myRules As Outlook.Rules
    Dim rl As Outlook.Rule
    Dim count As Integer
    Dim ruleList As String
    Dim rulePrefix As String
    Dim ruleFolder As Long

    '
    Dim outlookApp As Outlook.Application
    Dim objNS As NameSpace


    ruleFolder = olFolderJunk
    rulePrefix = "JUNK_FILTER_"

    Set objNS = Application.GetNamespace("MAPI")
    Set objJunkfolder = objNS.GetDefaultFolder(ruleFolder)

    ' get default store (where rules live)
    Set st = Application.Session.DefaultStore
    ' get rules
    Set myRules = st.GetRules

    ' iterate all the rules
    For Each rl In myRules
        ' determine if it's an Inbox rule and rule name prefix matches
        If rl.RuleType = olRuleReceive And Left(rl.Name, Len(rulePrefix)) = rulePrefix Then

            ' if so, run it
            rl.Execute ShowProgress:=True, Folder:=objJunkfolder
            count = count + 1
            ruleList = ruleList & vbCrLf & rl.Name
        End If
    Next

    ' tell the user what you did
    ruleList = "These rules were executed against the folder: " & objJunkfolder.Name & vbCrLf & ruleList
    MsgBox ruleList, vbInformation, "Macro: runRulesOnJunkFolder"

    Set rl = Nothing
    Set st = Nothing
    Set myRules = Nothing
    Set objJunkfolder = Nothing
    Set objNS = Nothing
End Sub
Related Question