Outlook 2016-规则向导中的“选择脚本”窗口为空

时间:2018-08-01 15:59:40

标签: vba outlook

我正在尝试运行以下宏将附件保存到计算机上的文件夹中:

Public Sub SaveAttachmentsToDisk(MItem As Outlook.MailItem)

    Dim oAttachment As Outlook.Attachment
    Dim sSaveFolder As String
    sSaveFolder = "R:\ConfigAssettManag\Performance\Let's see if this works"

    For Each oAttachment In MItem.Attachments
        oAttachment.SaveAsFile sSaveFolder & oAttachment.DisplayName
        Next

End Sub

由于某种原因,我无法将宏添加到Outlook中的规则。我读过here,我需要让它返回Outlook.MailItem,而我的代码已经做到了,所以我不知道为什么宏仍然不显示。Outlook Rule not showing my Macro

1 个答案:

答案 0 :(得分:0)

我认为答案有些晦涩,就像您必须这样声明ByRef:

Public Sub SaveAttachmentsToDisk(ByRef MItem As Outlook.MailItem)

让我为您节省很多时间。您会发现使用Outlook规则运行脚本无法解决问题。相反,您将希望在收到新邮件的实际事件上运行代码。这将更改代码的优先级,并使您摆脱Outlook规则中的所有疯狂错误。待会儿谢谢我。

将此代码放在“ ThisOutlookSession”对象中。它只能从那里开始。

Option Explicit
Private WithEvents inboxItems As Outlook.Items

' Set up the listener on the Inbox
Private Sub Application_Startup()
    Dim outlookApp As Outlook.Application
    Dim objectNS As Outlook.NameSpace

    Set outlookApp = Outlook.Application
    Set objectNS = outlookApp.GetNamespace("MAPI")
    Set inboxItems = objectNS.GetDefaultFolder(olFolderInbox).Items
End Sub

' Send new mail to the attachment processor
Private Sub inboxItems_ItemAdd(ByVal Item As Object)
    If TypeName(Item) = "MailItem" Then
        Dim EMail As Outlook.MailItem
        Set EMail = Item
        Debug.Print "Incoming Data."
        SaveAttachmentsToDisk EMail
        Set EMail = Nothing
    End If
End Sub

要保存文件,请尝试以下操作:

Dim fullPath As String
fullPath = sSaveFolder & oAttachment.FileName
oAttachment.SaveAsFile fullPath 

然后在fullPath行上中断,并在运行时检查该字符串的实际内容。这将帮助您查看文件的实际位置。