如何初始化事件处理程序

时间:2018-03-12 16:01:59

标签: vba outlook outlook-vba

我找到了这段代码online。它应该使用我提供的任何附件自动填充我的主题行。代码无法运行。

我没有收到错误或任何暗示它甚至通过代码的内容。

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 个答案:

答案 0 :(得分:1)

代码没有问题,你只需要初始化检查员

点击Sub Initialize_handlers()并按 F5

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

或者只是使用Application.Startup Event (Outlook),保存并重新启动Outlook然后它应该可以

实施例

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