Home > Enterprise >  Run rule from VBA fails
Run rule from VBA fails

Time:09-28

I want to be able 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.

I have tried to make the most simple VBA script in order to do that. For some reason, my Outlook rule is stored in the second store and not the default store.

When running the macro, the MsgBox is prompted, so the rule is found but it is not executed, and the e-mails in target are not moved as they should.

How can I improve my code in order to actually execute the rule.

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

CodePudding user response:

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
  • Related