Outlook电子邮件对话的最后一个元素不会触发VBA中的Application_ItemLoad事件

时间:2019-10-16 23:28:24

标签: vba events outlook outlook-vba

我编写了一个Visual Basic宏,以再次将打开的电子邮件标记为“未读”。 为此,我使用了事件“ Application_ItemLoad”,如下所示。但是,在对Outlook的按会话分组功能的电子邮件会话进行测试时,我发现有些奇怪:

通过双击打开此类对话组的最后一个元素,根本不会触发该事件。

请启发我,为什么每隔一封电子邮件都会触发此事件,而不会出现任何问题,而仅针对对话组的最后一个元素触发该事件。

1 个答案:

答案 0 :(得分:0)

我可能已经找到了。 在我的助手模块中,我有以下内容:
Public EventsDisable, unReadWhenSelected As Boolean

Stack Overflow post和Rick Rothstein对DailyDoseOfExcel.com的贡献中得知,用逗号分隔声明变量会导致第一个变量声明为 Variant 而不是预期的 Boolean

我只是更改为以下内容,并且错误消失了

Public EventsDisable As Boolean
Public unReadWhenSelected As Boolean

我仍然无法解释为什么将EventsDisable声明为 Variant 时会发生这种奇怪的错误。因此,如果有人知道,请放心。

Option Explicit

' When doubleclick opening unread mails, they are automatically marked 'read'. This code will mark them 'unread'.
' Despite that, emails that have been read already and then doubleclick opened will stay 'read'.
' In other words: Doubleclicking a mail won't change its unread property
Public WithEvents myItem As Outlook.mailItem

Private Sub Application_ItemLoad(ByVal Item As Object)
    MsgBox "Item loaded"
    'If EventsDisable = True Then Exit Sub
    If Item.Class = olMail Then
            Set myItem = Item
     End If
End Sub

Private Sub myItem_Read()
    unReadWhenSelected = myItem.UnRead
End Sub


Private Sub myItem_PropertyChange(ByVal Name As String)
    If EventsDisable = True Then Exit Sub
    If Name = "UnRead" Then
        If unReadWhenSelected = True And myItem.UnRead = False Then
            myItem.UnRead = True
            myItem.Save
        End If
    End If
End Sub