vbaoutlookrules

For Each loop results in "Automation Error = For Loop not Initialized"


I am looking to run all my Outlook rules from one button. I have the following code from another site.

It generates an error:

Run-time error -2146664191 (800c8101)
Automation Error

I have 22 rules but the code will only run the first rule which happens to be named "MKG". If I don't comment out the line On Error Resume Next it will run but then only runs the first rule that is "MKG".

The code falls over at Next with the Automation Error. The For Each rl in myRules seems to be correct but Next will not fire without the Automation Error message.

Sub RunAllInboxRules()
Dim st As Outlook.Store
Dim myRules As Outlook.Rules
Dim rl As Outlook.Rule
Dim count As Integer
Dim ruleList As String

On Error Resume Next
    
' 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;
        If rl.RuleType = olRuleReceive And rl.IsLocalRule = True Then
     'if so run it
        rl.Execute ShowProgress:=True
        count = count + 1
        ruleList = ruleList & vbCrLf & rl.name
    End If
  Next

' tell the user what you did
ruleList = "These rules were executed against the Inbox: " & vbCrLf & ruleList
MsgBox ruleList, vbInformation, "Macro: RunAllInboxRules"

Set rl = Nothing
Set st = Nothing
Set myRules = Nothing
End Sub

Since posting this question, I placed the same macro on my wife's PC and it runs without error. Both PCs are running Outlook 2019 Desktop under Windows 10Pro. This leads me to believe that my PC has a missing or corrupted file.

My PC runs another Outlook macro without issue.

If I comment it out On Error Resume Next the macro will fall over every time at Next with

Automation error - Loop not initialised

The problem seems to be anything with a loop such as For Each > Next or Do Until or Do While > Loop as even a simple macro with either Next or Loop results in

Automation Error = For Loop not Initialized


Solution

  • I created a new email profile and added the VBA code.

    The problematic macro now runs against two manually created rules. I haven't yet imported all my 22 rules for a complete test.