Copy method in ItemAdd generates Runtime Error - vba

When I run this code I get the error:
Run-Time error '-2147221233 (8004010f)':
The attempted operation failed. An object could not be found.
Everything is working despite the error.
The error disappears if I change the line
'MsgBox "Awesome"
to
MsgBox "Awesome"
A few tests showed that the error does occur if item.Sendername is used with the copy part. If I do just move the mail it works perfectly.
If I try to use the code separately it works without errors.
Private WithEvents snItems As Items
Private Sub Application_Startup()
Set snItems = Session.GetDefaultFolder(olFolderSentMail).Items
End Sub
Private Sub snItems_ItemAdd(ByVal item As Object)
Dim CopiedItem As MailItem
Dim ShareInbox As Outlook.MAPIFolder
Dim MapiNameSpace As Outlook.NameSpace
If TypeName(item) = "MailItem" Then
Set MapiNameSpace = Application.GetNamespace("MAPI")
Set ShareInbox = MapiNameSpace.Folders("Support").Folders("Send Mails")
If item.SenderName = "Support" Then
Set CopiedItem = item.Copy
CopiedItem.UnRead = True
CopiedItem.Move ShareInbox
End If
End If
'MsgBox "Awesome"
ExitRoutine:
Set ShareInbox = Nothing
Set CopiedItem = Nothing
Set MapiNameSpace = Nothing
End Sub
There is no error if not copied.
It is ok with the following Code
Set MapiNameSpace = Application.GetNamespace("MAPI")
Set ShareInbox = MapiNameSpace.Folders("Support").Folders("Gesendete Elemente")
If item.SenderName = "Support" Then
item.Move ShareInbox
End If

Copying the item adds an item to the Sent Items folder, triggering the ItemAdd code.
Disable the ItemAdd event temporarily.
Private Sub snItems_ItemAdd(ByVal item As Object)
Dim CopiedItem As MailItem
Dim ShareInbox As Outlook.MAPIFolder
Dim MapiNameSpace As Outlook.NameSpace
If TypeName(item) = "MailItem" Then
Set MapiNameSpace = Application.GetNamespace("MAPI")
Set ShareInbox = MapiNameSpace.Folders("Support").Folders("Send Mails")
If item.SenderName = "Support" Then
' Turn off event handling
Set snItems = Nothing
Set CopiedItem = item.Copy
CopiedItem.UnRead = True
CopiedItem.Move ShareInbox
' Turn on event handling
Set snItems = Session.GetDefaultFolder(olFolderSentMail).Items
End If
End If
ExitRoutine:
Set ShareInbox = Nothing
Set CopiedItem = Nothing
Set MapiNameSpace = Nothing
End Sub

Related

Set mails read if they were read in another folder

I'm trying to make an outlook macro, which will 'update' the mails. I have an Inbox folder and an another one. (2 mail accunts)
There is a rule, which is copying the mail from another folder to my inbox.
My goal is to set the mail as read in another folder, if it was read in the Inbox folder.
Sub precitane()
Dim myNameSpace As Outlook.NameSpace
Dim myInbox As Outlook.Folder
Dim myDestFolder As Outlook.Folder
Dim mydeffolder As Outlook.Folder
Dim items As Object
Dim defitems As Object
Set myNameSpace = Application.GetNamespace("MAPI")
Set myDestFolder = myNameSpace.Folders("") 'mymail
Set mydeffolder = myNameSpace.GetDefaultFolder(olFolderInbox)
For Each items In myDestFolder.items
For Each defitems In mydeffolder.items
If TypeOf items Is Outlook.MailItem & TypeOf defitems Is Outlook.MailItem Then
Dim oMail As Outlook.MailItem: Set oMail = items
Dim defMail As Outlook.MailItem: Set defMail = defitems
If oMail.SenderEmailAddress = "" & defMail.SenderEmailAddress = "" & defMail.Body = oMail.Body & defMail.UnRead = False Then
oMail.UnRead = True
oMail.Save
End If
End If
Next
Next
On Error GoTo 0
End Sub
"" contains my mail...
It looks like you tried with code from other than VBA.
I broke the If statement into separate parts as it is easier to follow and to debug.
Option Explicit
Sub precitane()
Dim myDestFolder As Folder
Dim mydeffolder As Folder
Dim item As Object
Dim defItem As Object
Set myDestFolder = Session.Folders("mailAddress2").Folders("Inbox").Folders("Test")
Set mydeffolder = Session.GetDefaultFolder(olFolderInbox).Folders("Test3")
For Each item In myDestFolder.items
If TypeOf item Is MailItem Then
For Each defItem In mydeffolder.items
If TypeOf defItem Is MailItem Then
If item.senderEmailAddress = defItem.senderEmailAddress Then
If item.Body = defItem.Body Then
If item.UnRead = False Then
defItem.UnRead = False
'If necessary
'item.Save
Exit For
End If
End If
End If
End If
Set defItem = Nothing
Next
End If
Set item = Nothing
Next
Debug.Print "Done."
End Sub

Move Email with ItemAdd

I'm attempting to move email with specific subject when received.
The mail is still in my Inbox. I've tested by sending mail from my account with specific subject.
Option Explicit
Private WithEvents inboxItems As Outlook.Items
Private Sub Application_Startup()
Dim outlookApp As Outlook.Application
Dim objectNS As Outlook.NameSpace
Set outlookApp = Outlook.Application
Set objectNS = outlookApp.GetNamespace("MAPI")
Set inboxItems = objectNS.GetDefaultFolder(olFolderInbox).Items
End Sub
Private Sub Items_ItemAdd(ByVal item As Object)
On Error GoTo ErrorHandler
Dim Msg As Outlook.MailItem
Set myInbox = GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
If TypeName(item) = "MailItem" Then
Set Msg = item
If InStr(0, Msg.Subject, "Testing Subject", vbTextCompare) > 0 Then
Set fldr = Outlook.Session.GetDefaultFolder(olFolderInbox).Folders("Testing")
Msg.Move fldr
End If
End If
ProgramExit:
Exit Sub
ErrorHandler:
MsgBox Err.Number & " - " & Err.Description
Resume ProgramExit
End Sub
I created this macro in ThisOutlookSession.
I think you may have an error with the naming of your Sub which means it doesn't fire
Items_ItemAdd => inboxItems_ItemAdd
As an addendum: I recently implemented a RegEx filter to incoming e-mails as I found I couldn't easily use rules to filter out some junk e-mail coming my way. This should be able to adapted to your needs (I've added the rule I think should work for you, but it's untested)
Within the 'ThisOutlookSession'
Private Sub Application_NewMailEx(ByVal EntryIDCollection As String)
On Error Resume Next
Call RegExFilterRules(EntryIDCollection)
End Sub
Within a module
Sub RegExFilterRules(ItemID As String)
' Requires Reference: Microsoft Scripting Runtime
Dim ThisNamespace As Outlook.NameSpace: Set ThisNamespace = Application.GetNamespace("MAPI")
Dim Inbox As Outlook.MAPIFolder: Set Inbox = ThisNamespace.GetDefaultFolder(olFolderInbox)
Dim Junk As Outlook.MAPIFolder: Set Junk = ThisNamespace.GetDefaultFolder(olFolderJunk)
Dim oMsg As Outlook.MailItem: Set oMsg = ThisNamespace.GetItemFromID(ItemID, Inbox.StoreID)
If Not oMsg Is Nothing And oMsg.Class = olMail Then
'If FindPattern(oMsg.Subject, "^M\d+$") Then oMsg.Move Junk ' oMsg.Delete
If FindPattern(oMsg.Subject, "^Testing Subject") Then oMsg.Move Inbox.Folders("Testing")
End If
End Sub
Private Function FindPattern(Str As String, Pattern As String) As Boolean
Dim RegEx As Object: Set RegEx = CreateObject("vbscript.RegExp")
With RegEx
.Global = True
.IgnoreCase = True
.MultiLine = True
.Pattern = Pattern
FindPattern = .Test(Str)
End With
End Function

Move Outlook incoming message to folder that starts with the same codes

I am trying to automate moving incoming messages to a designated subfolder in Outlook.
Messages that contain a projectnumber in the format P000.0000 should be moved to the Inbox's subfolder that starts with the same projectnumber.
The subfolders will be pre-created by hand, so the user can decide which projects to round up in a dedicated subfolder.
The folderstructure is Inbox>Actueel>P000.0000
The first bit, where incoming messages are checked works fine, but after that I get lost... Where it starts with For Each Folder In olFolderPrjcts
The error is on this line Set olFolder = objNS.GetDefaultFolder(olFolderInbox)
This is what I came up with so far:
Private WithEvents myOlItems As Outlook.Items
Private Sub Application_Startup()
Dim olApp As Outlook.Application
Dim objNS As Outlook.NameSpace
Dim olFolder As Outlook.MAPIFolder
Set olApp = Outlook.Application
Set objNS = olApp.GetNamespace("MAPI")
Set olFolder = objNS.GetDefaultFolder(olFolderInbox)
Set myOlItems = objNS.GetDefaultFolder(olFolderInbox).Items
End Sub
Private Sub myOlItems_ItemAdd(ByVal item As Object)
Dim Atts As Outlook.Attachments
Dim Props As Outlook.UserProperties
Dim Prop As Outlook.UserProperty
Dim PropName As String
PropName = "NumberAttachments"
Set Atts = item.Attachments
Set Props = item.UserProperties
Set Prop = Props.Find(PropName, True)
If Prop Is Nothing Then
Set Prop = Props.Add(PropName, olText, True)
End If
Dim olFolder As Outlook.MAPIFolder
Set olFolder = objNS.GetDefaultFolder(olFolderInbox)
Dim olFolderPrjcts
Set olFolderPrjcts = olFolder.Folders("actueel")
Prop.Value = Atts.Count
item.Save
Dim Msg As Outlook.MailItem
If TypeName(item) = "MailItem" Then
Set Msg = item
For Each Folder In olFolderPrjcts
If Left(Msg.Subject, 9) = Left(Folder.Name, 9) Then
Msg.Move (Folder)
End If
Next
' DO SOMETHING TO NEWLY ARRIVED MESSAGE
' If Msg.Subject contains like P000.0000 AND
' folder exists that starts with P000.0000
' then move to that folder
End If
End Sub
Without Option Explicit the error is likely Run-time error '424': Object required.
With Option Explicit the error is likely Compile error: Variable not defined.
Option Explicit
' Tools | Options | Editor tab
' Checkbox "Require Variable Declaration"
Private Sub myOlItems_ItemAdd(ByVal Item As Object)
Dim objNS As Namespace ' <--
Dim olFolder As folder
Dim folder As folder
Dim olFolderPrjcts As folder
Dim Msg As MailItem
Set objNS = GetNamespace("MAPI") ' <--
Set olFolder = objNS.GetDefaultFolder(olFolderInbox)
Set olFolderPrjcts = olFolder.Folders("actueel")
If TypeName(Item) = "MailItem" Then
Set Msg = Item
For Each folder In olFolderPrjcts.Folders
If Left(Msg.subject, 9) = Left(folder.name, 9) Then
'Debug.Print Msg.subject
'Debug.Print folder.name
Msg.move folder ' <-- no brackets
Exit For
End If
Next
End If
End Sub

Outlook VBA to save sent meeting requests/replies to a specified folder

I found the code below (here) to get outlook VBA to save sent email to a specified folder.
The code works well, however, any time that it runs on a sent meeting request or meeting reply, it errors.
I have been able to identify line 9 as the line where the error occurs:
Set Item.SaveSentMessageFolder = objFolder
My assumption, then, is that the Item.SaveSentMessageFolder code is incompatible with meeting-type objects. However, I am uncertain as to what the equivalent coding would be for meeting-type objects.
Can this code be modified to handle meeting-type objects in the same fashion that message-type objects are handled?
Private Sub Application_ItemSend(ByVal Item As Object, _
Cancel As Boolean)
Dim objNS As NameSpace
Dim objFolder As MAPIFolder
Set objNS = Application.GetNamespace("MAPI")
Set objFolder = objNS.PickFolder
If TypeName(objFolder) <> "Nothing" And _
IsInDefaultStore(objFolder) Then
Set Item.SaveSentMessageFolder = objFolder
End If
Set objFolder = Nothing
Set objNS = Nothing
End Sub
Public Function IsInDefaultStore(objOL As Object) As Boolean
Dim objApp As Outlook.Application
Dim objNS As Outlook.NameSpace
Dim objInbox As Outlook.MAPIFolder
On Error Resume Next
Set objApp = CreateObject("Outlook.Application")
Set objNS = objApp.GetNamespace("MAPI")
Set objInbox = objNS.GetDefaultFolder(olFolderInbox)
Select Case objOL.Class
Case olFolder
If objOL.StoreID = objInbox.StoreID Then
IsInDefaultStore = True
End If
Case olAppointment, olContact, olDistributionList, _
olJournal, olMail, olNote, olPost, olTask
If objOL.Parent.StoreID = objInbox.StoreID Then
IsInDefaultStore = True
End If
Case Else
MsgBox "This function isn't designed to work " & _
"with " & TypeName(objOL) & _
" items and will return False.", _
, "IsInDefaultStore"
End Select
Set objApp = Nothing
Set objNS = Nothing
Set objInbox = Nothing
End Function
At least one other person has found the property to be ineffective for meeting items.
https://msdn.microsoft.com/en-us/vba/outlook-vba/articles/meetingitem-savesentmessagefolder-property-outlook
"Setting or getting this property has no noticeable effect. Do not use this property."
Try monitoring the Sent Items folder.
Place this code in the ThisOutlookSession module.
Private WithEvents sentMailItems As items
Private Sub Application_Startup()
Set sentMailItems = Session.GetDefaultFolder(olFolderSentMail).items
End Sub
Private Sub sentMailItems_ItemAdd(ByVal Item As Object)
Dim objFolder As Folder
If TypeOf Item Is MeetingItem Then
Set objFolder = Session.PickFolder
If TypeName(objFolder) <> "Nothing" Then
Item.Move objFolder
End If
End If
Set objFolder = Nothing
End Sub

Code in Application_Quit() not Running (Outlook)

I've added some VBA code to my outlook application to run some clean-up when I close the program. Specifically, I delete any notification emails automatically generated by my test environment at work.
Then I try to empty my junk folder, mark emails in a specific folder as read, and then permanently delete all the items from my "Deleted Items" folder. Here is the code:
Private Sub Application_Quit()
On Error Resume Next
Call delete_LV_emails
Call mark_JIRA_read
Call empty_junk
Call empty_deleted
End Sub
The subs that I am calling are in a module named "Cleanup", and I know they all work when I run them on their own. However, only the "delete_LV_emails" sub gets called. That is, when I close/re-open outlook. The only thing that has occurred is that the automatically generated emails are moved to the "Deleted Items" folder. I can't figure out why only one of the subs is being called.
If it matters, the code for each of the subs is below:
Sub delete_LV_emails()
On Error Resume Next
Dim olNS As Outlook.NameSpace
Dim olFolder As Outlook.Folder
Dim olItem As Object
Dim arrKeys(0 To 1) As String
Set olNS = Application.GetNamespace("MAPI")
Set olFolder = olNS.GetDefaultFolder(olFolderInbox)
arrKeys(0) = "LabVIEW Error"
arrKeys(1) = "Test Complete"
iItemCount = olFolder.Items.Count
sDate = Split(Str(Now), " ")(0)
For iItemInd = iItemCount To 1 Step -1
Set olItem = olFolder.Items(iItemInd)
If Not Split(Str(olItem.CreationTime), " ")(0) = sDate Then GoTo NEXTITEM
iKeyInd = 0
While Not iKeyInd > 1
If InStr(olItem.Subject, arrKeys(iKeyInd)) Then olItem.Delete
iKeyInd = iKeyInd + 1
Wend
NEXTITEM:
Next
Set olNS = Nothing
Set olFolder = Nothing
Set olItem = Nothing
End Sub
Sub empty_deleted()
On Error Resume Next
Dim olNS As Outlook.NameSpace
Dim olFolder As Outlook.Folder
Dim olItem As Object
Set olNS = Application.GetNamespace("MAPI")
Set olFolder = olNS.GetDefaultFolder(olFolderDeletedItems)
iItemCount = olFolder.Items.Count
For iItemInd = iItemCount To 1 Step -1
Set olItem = olFolder.Items(iItemInd)
olItem.Delete
Next
Set olNS = Nothing
Set olFolder = Nothing
Set olItem = Nothing
End Sub
Sub empty_junk()
On Error Resume Next
Dim olNS As Outlook.NameSpace
Dim olFolder As Outlook.Folder
Dim olItem As Object
Set olNS = Application.GetNamespace("MAPI")
Set olFolder = olNS.GetDefaultFolder(olFolderJunk)
iItemCount = olFolder.Items.Count
For iItemInd = iItemCount To 1 Step -1
Set olItem = olFolder.Items(iItemInd)
olItem.Delete
Next
Set olNS = Nothing
Set olFolder = Nothing
Set olItem = Nothing
End Sub
Sub mark_JIRA_read()
On Error Resume Next
Dim olNS As Outlook.NameSpace
Dim olFolder As Outlook.Folder
Dim olItem As Object
Set olNS = Application.GetNamespace("MAPI")
Set olFolder = olNS.GetDefaultFolder(olFolderInbox).Folders("Jira")
iItemCount = olFolder.Items.Count
For iItemInd = iItemCount To 1 Step -1
Set olItem = olFolder.Items(iItemInd)
If olItem.UnRead Then olItem.UnRead = False
Next
Set olNS = Nothing
Set olFolder = Nothing
Set olItem = Nothing
End Sub
I realize that this is an extremely long-winded question, but if anyone has any insight I would greatly appreciate it.
Remove On Error Resume Next from your code then run it again
On Error Resume Next you are basically instructing VBA to essentially ignore the error and resume execution on the next line of code.
It is very important to remember that On Error Resume Next does not in any way "fix" the error. It simply instructs VBA to continue as if no error occurred.
See more info on
http://www.cpearson.com/excel/ErrorHandling.htm
The latest versions of Outlook do not call the Quit event handler. They do not pass Go and do not collect $200 - they just quit.
You can watch the Explorer.Close and Inspector.Close events - if there is only one Explorer or Inspector left (as reported by Application.Explorers.Count and Application.Inspectors.Count), Outlook is closing.