首页 > 解决方案 > Outlook 电子邮件对话的最后一个元素不会触发 VBA 中的 Application_ItemLoad 事件

问题描述

我编写了一个 Visual Basic 宏来将打开的电子邮件再次标记为“未读”。为此,我使用了事件“Application_ItemLoad”,如下所示。但是,在通过对话功能测试 Outlook 组的电子邮件对话时,我注意到一些奇怪的事情:

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

请告诉我为什么对于其他每封电子邮件,此事件都会触发而没有任何问题,但仅对于对话组的最后一个元素不会触发。

标签: vbaeventsoutlook

解决方案


我可能已经找到了。在我的帮助模块中,我有这个:
Public EventsDisable, unReadWhenSelected As Boolean.

从一篇很棒的Stack Overflow 帖子和 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

推荐阅读