My VBA code crashes when i try to set the variable to a specific rule

113 views Asked by At
Sub RunRuleMyRule()
    Dim myRule As Outlook.Rules
    Dim theRule As Outlook.Rule
    Set myRule = Application.Session.DefaultStore.GetRules()
    Set theRule = myRules.Item("rule1") 'get error here
    If theRule.Enabled Then
        theRule.Execute
    Else
        theRule.Enabled = True
        theRule.Execute
    End If
End Sub

When I debug it, theRule is "Nothing" and my code crashes. I am not sure what else can be done. I know the rule exists on the client and I've run the rule manually.

2

There are 2 answers

0
Paul Ogilvie On

At least to prevent crashing (I don't know why the rule cannot be found when you say it exists), try:

Set theRule = myRules.Item("rule1") 
If (theRule Is Nothing) Then Exit Sub
2
Eugene Astafiev On

The Item method of the Rules class obtains a Rule object specified by Index, which is either a numerical index into the Rules collection or the rule name.

Most probably you pass a wrong value to the method. Try to iterate over all rules and check their names to be sure such rule exists.

You may find the Getting Started with VBA in Outlook 2010 article helpful.