在Open of .oft上运行代码

时间:2016-09-09 02:49:36

标签: vba outlook

我希望下面的代码能够在打开.oft文件/电子邮件时运行。

我收到运行时91错误。

Public WithEvents myItem As Outlook.MailItem
Public EventsDisable As Boolean

Private Sub Application_ItemLoad(ByVal Item As Object)
    If EventsDisable = True Then Exit Sub
    Set myItem = Item
End Sub


Private Sub myItem_Open(Cancel As Boolean)
    EventsDisable = True
    Dim Insp As Inspector
    Dim obj As Object
    Set Insp = Application.ActiveInspector
    Set obj = Insp.CurrentItem

    obj.HTMLBody = Replace(obj.HTMLBody, "XXXX", Format(Now + 14, "MMMM dd, yyyy"))

    Set obj = Nothing
    Set Insp = Nothing

    EventsDisable = False
End Sub

如果我手动运行最后一个Sub myItem_Open作为公共子,它可以很好地工作。

1 个答案:

答案 0 :(得分:0)

您需要使用Inspectors.NewInspector事件(Inspectors可以检索Application.Inspectors)。

<强>更新即可。我的头顶

Public WithEvents myInspectors As Outlook.Inspectors

Private Sub Application_Startup()
  set  myInspectors = Application.Inspectors
  MsgBox "Application_Startup"
End Sub

Private Sub myInspectors_NewInspector(ByVal insp As Inspector)
    MsgBox "myInspectors_NewInspector"
    Set obj = Insp.CurrentItem
    obj.HTMLBody = Replace(obj.HTMLBody, "XXXX", Format(Now + 14, "MMMM dd, yyyy"))
    Set obj = Nothing
End Sub