Outlook VBA error extracting property data from GetRules collection

Status
Not open for further replies.

danno

Senior Member
Outlook version
Outlook 2016 64 bit
Email Account
IMAP
I created an Outlook VBA macro to allow the user to automatically create/run a rule to move the currently selected or opened email to a user-selected Outlook folder path. It will only create the rule if it doesn't already exists, and in either case it will prompt to run the rule on all message in the current folder.

It's been working OK until suddenly I'm getting a VBA error "-2147221233 The attempted operation failed. An object could not be found." (see green-highlighted line in the code below) trying to retrieve one of the rules. The rule that it's failing on has existed for years. Unlike the other rules that are based on acting on the sender's email address (or message header - that's due to the pervasive use of "<email address with random suffixes> on behalf of ..." used by allegedly legitimate commercial email vendors - don't get me started on that one :) ), this rule acts on 'selected properties' (via 'advanced search') then performs actions (deletes emails with blank subjects) and includes exceptions.

The only thing I could think of was perhaps the PST file was corrupt so I ran scanpst on it, but the error persists. I've been forced to incorporate a kludgy error handler to make the main loop that reads the Name property from each rule in the collection skip the offending item and continue. Would be useful to better understand what is causing this sudden failure. Here's the code snippet:

<code>
Sub CreateRuleFromSelectedSender()

Dim colRules As Outlook.rules
Dim oRule As Outlook.Rule
Dim colRuleActions As Outlook.RuleActions
Dim oMoveRuleAction As Outlook.MoveOrCopyRuleAction
Dim oFromCondition As Outlook.ToOrFromRuleCondition
Dim oMoveTarget, oCurrFolder As Outlook.folder
Dim oMsg As Outlook.MailItem
Dim strSenderEmail As String
Dim i As Integer
Dim bRuleFound As Boolean

On Error GoTo ErrHandler
'Assume that target folder already exists - must convert path to folder object
'Set oMoveTarget = GetFolder("\\C2PublicFolders\Test Folder\Test SubFolder\Dest Folder)

Set olApp = Outlook.Application
Set olSession = olApp.GetNamespace("MAPI")
Set oMoveTarget = olSession.PickFolder
If oMoveTarget Is Nothing Then
Set olApp = Nothing
Set olSession = Nothing
Exit Sub
End If

'Retrieve currently selected email message (or opened message)
Set oMsg = GetCurrentItem()

'Get Rules from Session.DefaultStore object
Set colRules = Application.Session.DefaultStore.GetRules() 'retrieve rules collection
Set oCurrFolder = Outlook.Application.ActiveExplorer.CurrentFolder 'retrieve currently selected folder (used when executing rule)
strSenderEmail = oMsg.SenderEmailAddress

'Determine if rule already exists for the sender's email address (don't want to create a duplicate)
bRuleFound = False
i = 1
Do While Not (bRuleFound) And i <= colRules.Count
'Look for rule named after strSenderEmail
If colRules.Item(i).Name = strSenderEmail Then
'If Rule name found, mark it as found and exit
bRuleFound = True
'run the rule without creating the duplicate
colRules.Item(i).Execute ShowProgress:=True, folder:=oCurrFolder
Else
Skip: i = i + 1
End If
Loop

'Create the rule by adding a Receive Rule to Rules collection, only if this doesn't already exist for this email address
If Not (bRuleFound) Then
Set oRule = colRules.Create(strSenderEmail, olRuleReceive)
Set oFromCondition = oRule.Conditions.From
With oFromCondition
.Enabled = True
.Recipients.Add (strSenderEmail)
.Recipients.ResolveAll
End With
'Specify the action in a MoveOrCopyRuleAction object - Action is to move the message to the target folder
Set oMoveRuleAction = oRule.Actions.MoveToFolder
With oMoveRuleAction
.Enabled = True
.folder = oMoveTarget
End With
'Update the rules collection and display progress dialog when running the rule
colRules.Save
'add code here to offer the option to run the rule now
If MsgBox("Run Rules Now?", vbYesNo) = vbYes Then oRule.Execute ShowProgress:=True, folder:=oCurrFolder
End If

Set colRules = Nothing
Set oRule = Nothing
Set oMoveTarget = Nothing
Set oMsg = Nothing
Exit Sub

ErrHandler:
Debug.Print Err.Number & vbTab & Err.Description
Resume Skip

End Sub
</code>
.
.
.
Ironically, with Outlook's convoluted object model, it turns out to be harder to specify a Outlook path (\\<mailbox store name>\folder\subfolder) path then to use the GetNameSpace("MAPI").pickfolder method, since the MoveToFolder method requires a folder object. I had to write a function GetFolder(<Outlook folder path>) to parse the path and return a folder object.
 
Was trying to edit the code snippet (I had HTML style <> instead of []), but now it's denying me from editing the post (it allowed it just a minute ago) ??!!
 
To answer your question, strSenderEmail does have the correct value of the the selected message email sender's email address, so that mystery remains.

I did encounter one additional problem. When the rule.execute method was invoked in a search folder (such as 'Unread Mail'), I'd get an VBA error "-2147024809 Sorry, something went wrong. You may want to try again.". If the rule was manually run via the Rules Manager, it would work fine. When I added the True property to the rule.execute method, it worked once but it showed that it was running the rule on folder Inbox, not Unread Mail (the current folder and oCurrFolder has that value and is being passed to rule.execute). After that, it fails again when run in Unread Mail search folder as before. This computer is running Office 2016 64-bit

On another computer running Outlook 2013 32-bit, I tried the same code on the same PST file and got the same 2 separate problems
  1. It chokes on the <rules collection>.item(x).name property on rules that it "doesn't like" (whether valid or not). I'm assuming they're valid, since Rules Manager is able to run these rules when selected.
  2. Even after either getting around that rule in the rules collection it doesn't like (either via error handler or by deleting the rule via Rules Manager), and the rule is saved, it still fails to run the rule.execute method on a search folder (i.e 'Unread Mail' and randomly, failing to run off of a 'search' result). It only seems to work properly is off of a named folder from the folder list. Again, as I stated earlier, Rules Manager has no problem running that rule. I even tried different parameters for rules.execute (like adding IncludeSubfolders:=true), although that is meaningless, since the default setting when running the rule via Rules Manager is IncludeSubfolders:=false.
Dazed and confused (listening to the Led Zeppelin tune now...) :)
 
To have an indication of a native VBA method available on a new mail compose that would be triggered at any written word / phrase (or as often as possible), or a guidance on how to create an observable of a dynamic form property.
Purpose:
One Outlook functionality that could be interesting to have is to know its readability values as the mail is composed. I know they can be obtained by doing the spell checker, but I'd like to avoid the burden of doing the spellcheck to get the result - I'd like to see numbers going up and down as the mail is written.
Problem:
I kind of created the function I'd need but I failed to find a method that could trigger it at every word written. I'd assume it'd be something like WordEditor_Change, HTMLBody_Change or something alike. It'd be similar to the Worksheet_Change we have in Excel, where values can be obtained as the Excel sheet is edited.
I tried to set an observable of WordEditor.words.count but also failed miserably.
What I have so far:
WithEvents myMail As Outlook.MailItem
Private Sub Application_ItemLoad(ByVal Item As Object)
Set myMail = Item
End Sub
Sub checkStatistics()
Dim objInsp As Outlook.Inspector
Set objInsp = myMail.GetInspector
'Enum Outlook: OlObjectClass (enumeración) (Outlook)
If objInsp.EditorType = olEditorWord Then ' outlook 2013
'Doc obj: Document object (Word)
Set objdoc = objInsp.WordEditor
Dim var As ClassHandlesEvent
Dim tst As classWithEvent
Set var = New ClassHandlesEvent
Set tst = New classWithEvent
var.EventVariable = tst
tst.value = objdoc.Words.Count
MsgBox objdoc.ReadabilityStatistics(9) & ": " & objdoc.ReadabilityStatistics(9).value & vbCrLf & "(Ideal values above 60)"
MsgBox objdoc.ReadabilityStatistics(8) & ": " & objdoc.ReadabilityStatistics(8).value & vbCrLf & "(Ideal values above 60)"
End If
Set objdoc = Nothing
Set objInsp = Nothing
End Sub
The below code that you execute
Set objdoc = objInsp.WordEditor
Gives you a WordDocument so now you have a WordVBA question instead of a OutlookVBA question. So you want an onchange event on changes to the document
 
Lewis-H, not sure what your last post has to do with the issues I presented with Outlook and how rules handling is turned into mush by VBA in 2 different ways (they work fine creating a rule by rules wizard or by running rules via Rules Manager).
 
VBA error "-2147024809 Sorry, something went wrong. You may want to try again.".
That code usually means the object can't be found.

Do you need to use rules or could you use a macro? If you are running the rules manually and not as mail arrives, a macro could work.



Or use a filing app - quick file is popular -
 
Didn't have correct notification settings, so I didn't see the latest response until now.

Didn't understand your response - I'm attempting to write a VBA macro to work with rules and it's failing the rule.execute method when the current folder is a search folder - nothing documented about such limitations with the rule.execute method. Running the same rule via the Outlook Rules and Alerts works fine and that's the issue - if it fails with VBA code, it should fail running manually.
 
Going back to my 4/4 post where I listed the 2 baffling error conditions:
  1. I gave up on this one - deleted the rule that was causing the issue, even though I was able to run the rule using the Rules Wizard (Manage Rules and Alerts, Run Rules Now, etc.) as I had stated originally. To me this is a bug in VBA with rule.execute (or perhaps a deliberately withheld capability - M$ has been known to play such games).
  2. I checked the Folder parameter value passed to rule.execute method when the macro is invoked from a search - that value is "All Mail Items" because the search scope is set for "All Mailboxes" and the macro fails as described. If I omit the Folder parameter, it defaults to Inbox and there are no problems. There is nothing documented about the rule.execute method that the Folder parameter can't be "All Mail Items", but at least in this case, running the rule manually via Rules Wizard also fails (nothing happens).
 
Going back to my 4/4 post where I listed the 2 baffling error conditions:
  1. I gave up on this one - deleted the rule that was causing the issue, even though I was able to run the rule using the Rules Wizard (Manage Rules and Alerts, Run Rules Now, etc.) as I had stated originally. To me this is a bug in VBA with rule.execute (or perhaps a deliberately withheld capability - M$ has been known to play such games).
  2. I checked the Folder parameter value passed to rule.execute method when the macro is invoked from a search - that value is "All Mail Items" because the search scope is set for "All Mailboxes" and the macro fails as described. If I omit the Folder parameter, it defaults to Inbox and there are no problems. There is nothing documented about the rule.execute method that the Folder parameter can't be "All Mail Items", but at least in this case, running the rule manually via Rules Wizard also fails (nothing happens).
 
Update on item 1 above - now solved:

The rule that VBA it was choking on (see 4/4 post) had an exception condition "except if sender in Contacts". This may have been caused by my Outlook Contacts (which is actually iCloud Contacts) had gotten corrupted and I was getting a "...set of folder cannot be opened..." error trying to open iCloud Contacts in Outlook (same with iCloud Calendar). This is apparently caused by a recent Windows Update - not sure which one - I rarely access the iCloud Contacts directly in Outlook, so this problem may have been 'lurking in the shadows' for some time. Once I pointed the Contacts portion of the rule exception to iCloud Contacts folder, the rule ran OK in VBA.

Now, with both issues solved, I can mark this issue as closed. Damn forum rules - won't let me delete accidentally duplicate prior post (didn't notice it until the 10 min had passed). Also, won't let me mark this reply as the solution. &^*%$#@!!
 
Status
Not open for further replies.
Similar threads
Thread starter Title Forum Replies Date
U Outlook 2019 VBA run-time error 424 Outlook VBA and Custom Forms 2
M VBA Code to Restart Outlook on error Outlook VBA and Custom Forms 3
M Outlook VBA Form not finding FOR LOOP -- Error message Outlook VBA and Custom Forms 2
Geldner Problem submitting SPAM using Outlook VBA Form Outlook VBA and Custom Forms 2
P VBA to add email address to Outlook 365 rule Outlook VBA and Custom Forms 0
M Outlook 2016 outlook vba to look into shared mailbox Outlook VBA and Custom Forms 0
D Outlook VBA forward the selected email to the original sender’s email ID (including the email used in TO, CC Field) from the email chain Outlook VBA and Custom Forms 2
L Fetch, edit and forward an email with VBA outlook Outlook VBA and Custom Forms 2
BartH VBA no longer working in Outlook Outlook VBA and Custom Forms 1
W Can vba(for outlook) do these 2 things or not? Outlook VBA and Custom Forms 2
richardwing Outlook 365 VBA to access "Other Actions" menu for incoming emails in outlook Outlook VBA and Custom Forms 0
J Outlook Rules VBA Run a Script - Multiple Rules Outlook VBA and Custom Forms 0
C Outlook (desktop app for Microsoft365) restarts every time I save my VBA? Using Outlook 1
E Outlook 365 Outlook/VBA Outlook VBA and Custom Forms 11
J VBA for outlook to compare and sync between calendar Outlook VBA and Custom Forms 1
E Outlook VBA change GetDefaultFolder dynamically Outlook VBA and Custom Forms 6
S vba outlook search string with special characters Outlook VBA and Custom Forms 1
G VBA to save selected Outlook msg with new name in selected network Windows folder Outlook VBA and Custom Forms 1
F Excel VBA to move mails for outlook 365 on secondary mail account Outlook VBA and Custom Forms 1
K Outlook Office 365 VBA download attachment Outlook VBA and Custom Forms 2
V vBA for searching a cell's contents in Outlook and retrieving the subject line Outlook VBA and Custom Forms 1
B vBA for exporting excel file from outlook 2016 Outlook VBA and Custom Forms 3
S Excel vba code to manage outlook web app Using Outlook 10
H Custom Outlook Contact Form VBA Outlook VBA and Custom Forms 1
S Problem Checking the available stores in my Inbox (Outlook VBA) Outlook VBA and Custom Forms 0
S Outlook VBA How to adapt this code for using in a different Mail Inbox Outlook VBA and Custom Forms 0
O VBA Outlook Message Attachment - Array Index Out of Bounds Outlook VBA and Custom Forms 0
J Want to learn VBA Macros for Outlook. What book can you recommend? Outlook VBA and Custom Forms 2
M Outlook 2013 reminder email by using Outlook vba Outlook VBA and Custom Forms 2
O Email not leaving Outbox when using Excel VBA to sync Outlook account Outlook VBA and Custom Forms 4
L Moving emails with similar subject and find the timings between the emails using outlook VBA macro Outlook VBA and Custom Forms 1
B Outlook Business Contact Manager with SQL to Excel, User Defined Fields in BCM don't sync in SQL. Can I use VBA code to copy 1 field to another? BCM (Business Contact Manager) 0
N How can I increase/faster outlook VBA Macro Speed ? Using Outlook 2
N Outlook Email Rule execution through shortcut keys (VBA codes) Using Outlook 1
A VBA Code in Outlook disappears after first use Outlook VBA and Custom Forms 1
dweller Outlook 2010 Rule Ignores VBA Script Outlook VBA and Custom Forms 2
G Outlook VBA and Google Calendar ("Events") Outlook VBA and Custom Forms 1
J VBA Outlook : Subject line : Cut and Paste name to heading , number to very end of the body of Email Outlook VBA and Custom Forms 1
B Advanced Search in MS Outlook by VBA and SQL Outlook VBA and Custom Forms 2
K Outlook Archive to PST Files by Date Range VBA Script? Outlook VBA and Custom Forms 1
J Help Please!!! Outlook 2016 - VBA Macro for replying with attachment in meeting invite Outlook VBA and Custom Forms 9
S Find a cell value in excel using outlook vba Using Outlook 1
J Execute Add-In Button from VBA Outlook 2016 Outlook VBA and Custom Forms 1
J Open an outlook email by Subject on MS Access linked table with VBA Outlook VBA and Custom Forms 10
D create an html table in outlook custom form 2010 using vba in MsAccess Outlook VBA and Custom Forms 7
M Slow VBA macro in Outlook Outlook VBA and Custom Forms 5
T Outlook AntiSpam with VBA Outlook VBA and Custom Forms 1
F "Move to" O365 feature to Outlook client via VBA Outlook VBA and Custom Forms 4
B query outlook using vba Outlook VBA and Custom Forms 13
J VBA to switch Outlook online/offline Outlook VBA and Custom Forms 4

Similar threads

Back
Top