I'm attempting to have emails coming in to my main inbox (for testing, future second inbox) be routed to a subfolder. I want it to activate on all items on receipt. However, on the last line of the VBA code, Item.Move olnamespace.Folders("My Name").Folders("Inbox").Folders("Subfolder") fails with a run-time error 91. I'm not sure why and have attempted to troubleshoot it. VBA - let alone outlook side - is very new to me.
Private WithEvents secondinboxitems As Outlook.Items
Sub initializesecondinboxitems()
Dim olapp As Outlook.Application
Dim olnamespace As Outlook.NameSpace
Dim secondinboxfolder As Outlook.Folder
'initialize outlook application and namespace
Set olapp = New Outlook.Application
Set olnamespace = olapp.GetNamespace("MAPI")
'specify the folder containing the emails in the second inbox
Set secondinboxfolder = olnamespace.Folders("My Name").Folders("Inbox")
'get the items collection for the second inbox folder
Set secondinboxitems = secondinboxfolder.Items
End Sub
Private Sub secondinboxitems_ItemAdd(ByVal Item As Object)
'code to process the items
Dim olapp As Outlook.Application
Dim olnamespace As Outlook.NameSpace
Dim keyword As String
'set the keywords to search for.
keyword = "Keyword"
'check if the received item is a mail item
If TypeOf Item Is Outlook.MailItem Then
'read email body as plain text
Dim body As String
body = Item.body
'check if keyword is present
If InStr(1, body, keyword, vbTextCompare) > 0 Then
'Dim itemtomove As Outlook.MailItem
'Set itemtomove = Item
Item.Move olnamespace.Folders("My Name").Folders("Inbox").Folders("Subfolder")
End If
End If
End Sub
Is what I am working with. I tried assigning the item as a mail item more specifically. And, I tried re-setting GetNamespace("MAPI"). I assumed neither would be an issue. And i guess confirmed that when it didn't solve the problem. Any pointers on why the sub is failing on item.move would be appreciated.
Also! It seems to be reading the emails for the keyword base on a debug.print of the text compare.
Re: Your comment
tried;
Which, once again has the error.
olappdoes not exist inPrivate Sub secondinboxitems_ItemAdd(ByVal Item As Object).Try this cleaned up code to decrease the confusion.