For Each 循环会导致“自动化错误 = For 循环未初始化”

问题描述 投票:0回答:2

我希望通过一个按钮运行我的所有 Outlook 规则。我从另一个网站得到了以下代码。

它会产生错误:

运行时错误-2146664191 (800c8101)
自动化错误

我有 22 条规则,但代码只会运行第一个规则,该规则恰好名为“MKG”。如果我不注释掉该行

On Error Resume Next
它将运行,但随后仅运行第一个规则“MKG”。

代码因自动化错误而在

Next
处失败。
For Each rl in myRules
似乎是正确的,但如果没有自动化错误消息,
Next
将不会触发。

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

自从发布这个问题后,我在我妻子的电脑上放置了相同的宏,并且它运行没有错误。两台电脑都在 Windows 10Pro 下运行 Outlook 2019 桌面版。这让我相信我的电脑文件丢失或损坏。

我的电脑运行另一个 Outlook 宏没有问题。

如果我将其注释掉

On Error Resume Next
,宏每次都会在
Next

处倒下

自动化错误 - 循环未初始化

问题似乎是任何带有循环的东西,例如

For Each
>
Next
Do Until
Do While
>
Loop
,即使是带有
Next
Loop
的简单宏也会导致

自动化错误 = For 循环未初始化

vba outlook rules
2个回答
0
投票

在找到合理的解释之前,请尝试索引循环。

Option Explicit

Sub RunAllInboxRulesIndexedLoop()

    ' base code
    ' https://www.slipstick.com/outlook/rules/run-outlook-rules-startup/
    
    Dim st As Store
    Dim myRules As Rules
    Dim rl As Rule
    
    Dim count As Long
    Dim ruleList As String
    
    ' get default store (where rules live)
    Set st = Session.defaultStore
    
    ' get rules
    Set myRules = st.GetRules
    
    ' iterate rules with an indexed loop
    Dim i As Long
    For i = 1 To myRules.count
    
        ' determine if it's an Inbox rule
        Set rl = myRules(i)
        Debug.Print "rl.Name: " & rl.Name
        Debug.Print " rl.RuleType: " & rl.RuleType
        
        If rl.RuleType = olRuleReceive Then
        
            Debug.Print " rl.IsLocalRule: " & rl.IsLocalRule
            If rl.IsLocalRule = True Then
                'if so run it
                rl.Execute ShowProgress:=True
                count = count + 1
                Debug.Print " count: " & count & " of " & i
                ruleList = ruleList & vbCrLf & rl.Name
            End If
            
        End If
        
    Next
    
    ' tell the user what you did
    ruleList = "These rules were executed against the Inbox: " & vbCrLf & ruleList
    MsgBox ruleList, vbInformation, "Macro: RunAllInboxRules"

End Sub

0
投票

我创建了一个新的电子邮件配置文件并添加了 VBA 代码。

有问题的宏现在针对两个手动创建的规则运行。我尚未导入所有 22 条规则以进行完整测试。

© www.soinside.com 2019 - 2024. All rights reserved.