Implementing an interface in ThisOutlookSession is not working in Office 2013 - vba

I have an Outlook macro I wrote that will automatically mark items as read when I move them to a folder. (I hate having unread messages in folders other than my Inbox.) I wrote the macro in Outlook 2010, and it's been functioning well for years.
I recently upgraded to Office 2013, and now my macro doesn't work--I'm getting a type mismatch error on this line (see below for the full code):
Set oMoveHandler.Callback = Me
oMoveHandler.Callback expects an object of type IMessageMoved, which the object implements, so I'm not sure why I'm getting this error. Any ideas?
ThisOutlookSession code:
Option Explicit
Implements IMessageMoved
Private m_oFolderCollection As Collection
Private Sub Application_Quit()
Set m_oFolderCollection = Nothing
End Sub
Private Sub Application_Startup()
Dim oFolder As Outlook.Folder
Set m_oFolderCollection = New Collection
For Each oFolder In Application.GetNamespace("MAPI").Folders
Call AddFolder(oFolder)
Next oFolder
End Sub
Private Sub AddFolder(Folder As Outlook.Folder)
Dim oFolder As Outlook.Folder
Dim oMoveHandler As MoveHandler
If Folder Is Nothing Then
Exit Sub
End If
If Folder.Folders.Count = 0 Then
Exit Sub
End If
For Each oFolder In Folder.Folders
If oFolder.DefaultItemType = olMailItem Then
If oFolder.Name <> "Inbox" And oFolder.Name <> "Outbox" And oFolder.Name <> "ePrescribing Workgroup" Then
Set oMoveHandler = New MoveHandler
Set oMoveHandler.Folder = oFolder.Items
Set oMoveHandler.Callback = Me
Call m_oFolderCollection.Add(oMoveHandler)
Set oMoveHandler = Nothing
End If
Call AddFolder(oFolder)
End If
Next oFolder
End Sub
Private Function IMessageMoved_MessageMoved(Item As Object) As Variant
On Error Resume Next
Item.UnRead = False
On Error GoTo 0
End Function
IMessageMoved:
Public Function MessageMoved(Item As Object)
End Function
MoveHandler:
Private WithEvents m_oFolder As Outlook.Items
Private m_oCallback As IMessageMoved
Public Property Set Folder(Folder As Outlook.Items)
Set m_oFolder = Folder
End Property
Public Property Get Folder() As Outlook.Items
Set Folder = m_oFolder
End Property
Public Property Set Callback(Object As IMessageMoved)
Set m_oCallback = Object
End Property
Private Sub Class_Terminate()
Set m_oFolder = Nothing
Set m_oCallback = Nothing
End Sub
Private Sub m_oFolder_ItemAdd(ByVal Item As Object)
If Not m_oCallback Is Nothing Then
Call m_oCallback.MessageMoved(Item)
End If
End Sub

I suspect I was actually running into a similar issue to the one described in this post describing a similar problem in Excel where binding just wasn't working as expected. To work around it, I ended up moving my interface out of ThisOutlookSession into a separate class which I then just instantiate from ThisOutlookSession.

Related

ItemAdd runs a few times then stops working until I restart Outlook

I want to run a code every time a new email arrives in the inbox.
The following code is within 'ThisOutlookSession'
Public WithEvents oItems as Outlook.Items
Private Sub Application.Startup()
Set oItems = session.GetDefaultFolder(olFolderInbox).items
End sub
Private sub oItems_ItemAdd(ByVal item as object)
Debug.print "New email detected"
End sub
This code runs for 1 - 5 new emails. After that, it won't execute unless I close Outlook and reopen.
It is as if oItems loses connection to the 'session'.
You can paste this in ThisOutlookSession
Private Sub Application_NewMailEx(ByVal EntryIDCollection As String)
Dim oNewMailItem As Outlook.MailItem
Dim appNameSpace As Outlook.NameSpace
Set appNameSpace = Application.Session
Select Case appNameSpace.GetItemFromID(EntryIDCollection).Class
Case Is = olMail
Set oNewMailItem = appNameSpace.GetItemFromID(EntryIDCollection)
End Select
End Sub
The event returns the object ID, the object ID is used to get the object. If the object is an email then it is saved as a local variable.
Alternatively, you may not want to 'muddy up' ThisOutlookSession so you can use a custom class and expose the mail as a public property.
In ThisOutlookSession you'd have:
Public cNewMailEx As clsNewMailEx
Private Sub Application.Startup()
Set cNewMailEx = New clsNewMailEx
End sub
In a class module named clsNewMailEx you'd have:
Option Explicit
Private WithEvents olApp As Outlook.Application
Private pMailItem As Outlook.MailItem
Public Property Get NewMailItem() As Outlook.MailItem
Set NewMailItem = pMailItem
End Property
Private Sub Class_Initialize()
Set olApp = Outlook.Application
End Sub
Private Sub olApp_NewMailEx(ByVal EntryIDCollection As String)
Dim appNameSpace As Outlook.NameSpace
Set appNameSpace = Application.Session
Select Case appNameSpace.GetItemFromID(EntryIDCollection).Class
Case Is = olMail
Set pMailItem = appNameSpace.GetItemFromID(EntryIDCollection)
End Select
End Sub
Now, anywhere in your application, you can retrieve the new email with cNewMailEx.NewMailItem
NewMailEx is the preferred alternative for the inbox.
For other folders, you could run Application_Startup without closing Outlook.
Remove Private from Private Sub Application_Startup().
1 - You may assign Application_Startup to a button.
2 - To make manual invoking less frequent call Application_Startup from existing code you normally run during the day.

How to set reminder for incoming or outgoing meeting requests

When I create/update meeting requests OR receive a meeting request (skype/team meeting or regular meeting), I want to check if a reminder has been set. If not, set a reminder for 15 minutes before the meeting.
Some searching brought me code I included in the "ThisOutlookSession" module. No reminders are added.
Public WithEvents objCalendar As Outlook.Folder
Public WithEvents objCalendarItems As Outlook.Items
Private Sub Application_Startup()
Set objCalendar = Outlook.Application.Session.GetDefaultFolder(olFolderCalendar)
Set objCalendarItems = objCalendar.Items
End Sub
Private Sub objCalendarItems_ItemAdd(ByVal Item As Object)
Call SetReminder(Item)
End Sub
Private Sub objCalendarItems_ItemChange(ByVal Item As Object)
Call SetReminder(Item)
End Sub
Private Sub SetReminder(ByVal objCalendarItem As Object)
If TypeOf Item Is MeetingItem Then
Set objMeetingRequest = Item
Set objMeeting = objMeetingRequest.GetAssociatedAppointment(True)
'Check if reminder existing
If objMeeting.ReminderSet = False Then
objMeeting.ReminderSet = True
objMeeting.ReminderMinutesBeforeStart = 15
objMeeting.Save
End If
End If
End Sub
First of all, there is no Item object passed to the SetReminder method.
You need to check for AppointmentItem instead of MeetingItem in the code.
Private Sub SetReminder(ByVal objCalendarItem As Object)
Dim objMeeting as AppointmentItem
If TypeOf objCalendarItem Is AppointmentItem Then
Set objMeeting = objCalendarItem
'Check if reminder existing
If objMeeting.ReminderSet = False Then
objMeeting.ReminderSet = True
objMeeting.ReminderMinutesBeforeStart = 15
objMeeting.Save
End If
End If
End Sub
If required you may check out the MeetingStatus property.

Send As a Delegate or a Distribution Group by default

We modified the code from this tutorial to allow us to change default send on behalf address for two mailboxes. https://www.howto-outlook.com/howto/setfromaddress.htm#quickinstall
It works perfectly in new window reply but doesn't work in reply pane.
What could be the issue?
Here is the code:
Dim WithEvents objInspectors As Outlook.Inspectors
Dim WithEvents objMailItem As Outlook.MailItem
Dim WithEvents myOlExp As Outlook.Explorer
Private Sub Application_Startup()
Initialize_handler
End Sub
Public Sub Initialize_handler()
Set objInspectors = Application.Inspectors
Set myOlExp = Application.ActiveExplorer
End Sub
Private Sub objInspectors_NewInspector(ByVal Inspector As Inspector)
If Inspector.CurrentItem.Class = olMail Then
Set objMailItem = Inspector.CurrentItem
If objMailItem.Sent = False Then
Call SetFromAddress(objMailItem)
End If
End If
End Sub
Public Sub SetFromAddress(objItem As Outlook.MailItem)
If objItem.SentOnBehalfOfName = "info#domain1.com" Then
For i = 1 To Session.Accounts.Count
If Right(Session.Accounts(i).DisplayName, Len("#domain1.com")) = "#domain1.com" Then
objItem.SentOnBehalfOfName = Session.Accounts(i).DisplayName
Exit For
End If
Next i
Else
For i = 1 To Session.Accounts.Count
If Right(Session.Accounts(i).DisplayName, Len("#domain2.com")) = "#domain2.com" Then
objItem.SentOnBehalfOfName = Session.Accounts(i).DisplayName
Exit For
End If
Next i
End If
End Sub
'Uncomment the next 3 lines to enable Outlook 2013/2016/365 Reading Pane Reply
Private Sub myOlExp_InlineResponse(ByVal objItem As Object)
Set objMailItem = objItem
Call SetFromAddress(objMailItem)
End Sub
Inline reply won't fire the Inspector.NewInspector event. You need to use Explorer.InlineResponse event. Explorer object (assuming you only use one Explorer throughout the Outlook session) can be retrieved from Application.ActiveExplorer.

Only valid in object module

I'm getting this error:
only valid in object module
when I'm trying to run the script below on VBA outlook 2016.
Private WithEvents myItem As outlook.MailItem
Private Sub myItem_AttachmentRead(ByVal myAttachment As Outlook.Attachment)
If myAttachment.Type = olByValue Then
MsgBox "If you change this file, also save your changes to the original file."
End If
End Sub
Public Sub TestAttachRead()
Dim atts As Outlook.Attachments
Dim myAttachment As Outlook.Attachment
Set myItem = Application.ActiveExplorer.CurrentFolder.Items("Test")
Set atts = myItem.Attachments
myItem.Display
End Sub
The following vba code Must be under ThisOutlookSession module
Private WithEvents myItem As outlook.MailItem
Private Sub myItem_AttachmentRead(ByVal myAttachment As Outlook.Attachment)
If myAttachment.Type = olByValue Then
MsgBox "If you change this file, also save your changes to the original file."
End If
End Sub
And the following vba code could be on regular module
Public Sub TestAttachRead()
Dim atts As Outlook.Attachments
Dim myAttachment As Outlook.Attachment
Set myItem = Application.ActiveExplorer.CurrentFolder.Items("Test")
Set atts = myItem.Attachments
myItem.Display
End Sub
I'm presuming this code is currently on a standard VBA module. You cannot have an WithEvents variable on such modules. It must be either a class module or a document module (e.g. one of Outlook's code-behind for instance) in order to receive events from that mail item.

VBA Outlook 2010: Monitor new emails in public fodler

whenever a new mail arrives in a public folder, I would like a MsgBox to pop up. I solved this for my own inbox using this code:
Private Sub Application_NewMail()
Dim oNS As NameSpace
Dim oFolder As MAPIFolder
Dim oNewMail As MailItem
Set oNS = Application.GetNamespace("MAPI")
Set oFolder = oNS.GetDefaultFolder(olFolderInbox)
Set oNewMail = oFolder.Items.GetFirst
MsgBox oNewMail.subject
End Sub
I also managed to access and retrieve the latest email from the public folder by replacing:
Set oFolder = oNS.GetDefaultFolder(olFolderInbox)
by
Set oFolder = oNS.Folders(2).Folders(2).Folders("XX").Folders("XX")
Howver, this obviously only works, when I manually evalute the code since the code is only executed when a new mail arrives in my inbox. I did some googling and found a potential solution to monitor a public folder:
Private WithEvents TestMail As Items
Public Sub Application_Startup()
Set TestMail = Application.GetNamespace("MAPI").Folders(2).Folders(2).Folders("XX").Folders("XX").Items
End Sub
Private Sub TestMail_ItemAdd(ByVal Item As Object)
MsgBox ("new mails arrived")
End Sub
Edit - The error when compiling: Unknown attribute in sub or function. I am using Outlook 2010 professional.
Try to use the following code:
Private WithEvents NewMail As Items
Public Sub Application_Startup()
Set NewMail = Application.GetNamespace("MAPI").Folders(2).Folders(2).Folders("XX").Folders("XX").Items
End Sub
Private Sub NewMail_ItemAdd(ByVal Item As Object)
MsgBox ("new mails arrived")
End Sub
However, I'd recommend breaking the long chain of calls:
Set NewMail = Application.GetNamespace("MAPI").Folders(2).Folders(2).Folders("XX").Folders("XX").Items
and declare each property or method call on a separate line of code. Thus, you will find the exact ptoperty or method call which generates the error.
You may find the How to get reference to Public Folder Store using Outlook Object Model for Outlook 2010? article helpful.