Outlook 2010 Macro throws VBA error 'For loop not initialized'
I got this bit of code from someone's blog years ago. It basically iterates through all the Outlook mail rules, and executes them (handy to organize your inbox!). I've recently upgrade to Outlook 2010 from 2007. Now I get a very strange error stating
Run-time erro开发者_开发技巧r '92':
For loop not initialized
However, while debugging this, it will always run through 8 times (out of 20-25), then it throw this error.
Here is the offending code:
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
'get default store (where rules live) & get rules
Set st = Application.Session.DefaultStore
Set myRules = st.GetRules
'iterate all the rules
For Each rl In myRules
If rl.RuleType = olRuleReceive Then 'determine if it’s an Inbox rule, 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
Edit:
Per Jay Riggs's comment, clearing the entire for block still results in the error.
I'd replace this loop with something like:
Dim k as Long
For k = 1 To myRules.Count ' might be 0-based, didnt check
set rl = myRules(k)
If rl.RuleType = olRuleReceive Then 'determine if it’s an Inbox rule, if so, run it
rl.Execute ShowProgress:=True
count = count + 1
ruleList = ruleList & vbCrLf & rl.Name
End If
Next
I bet there is some rule at position 8 or 9 that doesn't fit into the myRules
collection and that throws the error. You can also check the myRules
collection at the offending point. Maybe Office 2007 was more forgiving and skipped that entry.
So the issue ended up being that some of the rules referred to a PST file I missed on moving to my new machine. Thanks to Justin for forcing me to take a deeper look at the rules!
+1 to the obscure error message for this.
精彩评论