How to initialize an event handler

筅森魡賤 提交于 2019-12-13 01:36:26

问题


I found this code online. It is supposed to auto populate my subject line with any attachments I provide. The code does not run.

I don't receive an error or anything that suggests its even going through the code.

Public WithEvents olInspectors As Outlook.Inspectors
Public WithEvents olMail As Outlook.MailItem

Private Sub Initialize_handlers()
    Set olInspectors = Application.Inspectors
End Sub

Private Sub olInspectors_NewInspector(ByVal Inspector As Inspector)
    Dim olItem As Object
    Set olItem = Inspector.CurrentItem
    If TypeName(olItem) = "MailItem" Then Set olMail = olItem
End Sub

Private Sub olMail_AttachmentAdd(ByVal Attachment As Attachment)
    MsgBox "This is a test."
    If olMail.Subject = "" Then
      'If you don't want the prompt,
      'Just delete the Msgbox line and its corresponding "End if".
      If MsgBox("Do you want to use the attachment name as the subject", vbYesNo) = vbYes Then
         olMail.Subject = Attachment.DisplayName
      End If
    End If
End Sub

回答1:


There is nothing wrong with code, you simply need to Initialize the Inspectors

Click on Sub Initialize_handlers() and press F5

Private Sub Initialize_handlers()
    Set olInspectors = Application.Inspectors
End Sub

Or just use Application.Startup Event (Outlook), Save it and restart Outlook then it should work

Example

Public WithEvents olInspectors As Outlook.Inspectors
Public WithEvents olMail As Outlook.mailitem

Private Sub Application_Startup()
    Set olInspectors = Application.Inspectors
End Sub

Private Sub Initialize_handlers()
    Set olInspectors = Application.Inspectors
End Sub

Private Sub olInspectors_NewInspector(ByVal Inspector As Inspector)
    Dim olItem As Object
    Set olItem = Inspector.CurrentItem
    If TypeName(olItem) = "MailItem" Then Set olMail = olItem
End Sub

Private Sub olMail_AttachmentAdd(ByVal Attachment As Attachment)
    MsgBox "This is a test."
    If olMail.Subject = "" Then
      'If you don't want the prompt,
      'Just delete the Msgbox line and its corresponding "End if".
      If MsgBox("Do you want to use the attachment name as the subject", _
                                                     vbYesNo) = vbYes Then
         olMail.Subject = Attachment.DisplayName
      End If
    End If
End Sub


来源:https://stackoverflow.com/questions/49239607/how-to-initialize-an-event-handler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!