Search code examples
vbaoutlook-2016

Run rule from second store


I want to run a rule from a macro/button in ribbon instead of going through all the clicks needed to "Run rules now" manually. Using Outlook 2016.

My Outlook rule is stored in the second store and not the default store.

The MsgBox is prompted, so the rule is found but it is not executed, and the e-mails in target are not moved.

Sub RunRule()
    Dim rules As Outlook.rules
    
    Set rules = Application.Session.Stores(2).GetRules()
    
    rules.Item("kundeordre").Execute ShowProgress:=True
    
    MsgBox rules.Item("kundeordre")
End Sub

The rules in Outlook:
The rules


Solution

  • For rules in a non-default store, specify the folder.

    Option Explicit
    
    Sub RunRule()
    
        ' https://learn.microsoft.com/en-us/office/vba/api/outlook.rule.execute
        
        Dim olRules As rules
        
        Dim myRule As Rule
        Dim myRuleName As String
            
        Dim olStore As Store
        Dim olFolder As Folder
        
        Set olStore = Session.Stores(2)
        Debug.Print olStore
        
        With olStore
            Set olRules = .GetRules()
            Set olFolder = .GetDefaultFolder(olFolderInbox)
        End With
        
        myRuleName = "kundeordre"
         
        For Each myRule In olRules
            Debug.Print "myRule " & myRule
            If myRule = myRuleName Then
                ' Folder required for non-default store
                myRule.Execute ShowProgress:=True, Folder:=olFolder
                MsgBox myRule & " executed in " & olStore
                Exit For
            End If
        Next
        
    End Sub