【问题标题】:Trigger a macro after a new email with specific subject在具有特定主题的新电子邮件后触发宏
【发布时间】:2019-05-09 10:03:18
【问题描述】:

根据电子邮件主题运行 excel 宏

我已经找到了一种在找到新电子邮件时触发宏的方法。但是,我只想在电子邮件主题行中有特定单词时触发它。这是我发现的 JimmyPena 发布的代码行。

Private WithEvents Items As Outlook.Items
Private Sub Application_Startup() 
  Dim olApp As Outlook.Application 
  Dim objNS As Outlook.NameSpace 
  Set olApp = Outlook.Application 
  Set objNS = olApp.GetNamespace("MAPI") 

  ' default local Inbox
  Set Items = objNS.GetDefaultFolder(olFolderInbox).Items 
End Sub

Private Sub Items_ItemAdd(ByVal item As Object) 

  On Error Goto ErrorHandler 
  Dim Msg As Outlook.MailItem 

  If TypeName(item) = "MailItem" Then
    Set Msg = item 
    ' ******************
    ' I call my macro here
    ' ******************
  End If
ProgramExit: 
  Exit Sub
ErrorHandler: 
  MsgBox Err.Number & " - " & Err.Description 
  Resume ProgramExit 
End Sub

我想如果我把这部分If TypeName(item) = "MailItem" Then改成 If TypeName(item) = "MailItem" And Msg.Subject = "specific_subject_here" Then 它现在应该只在新电子邮件的主题行包含特定主题时触发宏,但我收到此错误:91-Object variable or with block variable not set。这是否意味着我还必须将 Msg 声明为一个对象,是否可以将它与 TypeName 函数结合起来?

【问题讨论】:

  • Set 之前,您不能使用Msg。你可以添加第二个If Msg.Subject Set Msg...之后。

标签: excel vba outlook


【解决方案1】:

该错误消息几乎不言自明:您正在尝试使用尚未Set 的对象。

相反,添加一个额外的If Msg.Subject Set msg...

If TypeName(item) = "MailItem" Then
    Set Msg = item 

    If Msg.Subject = "specific subject" Then
    ' ******************
    ' I call my macro here
    ' ******************
    End If
End If

【讨论】: