2016-12-08 78 views
0

使用Outlook 2016 for Windows(10)。Outlook VBA - BeforeDelete不起作用

我想写一些VBA来自动将我删除的电子邮件复制到一个单独的文件夹(或者也许只是复制覆盖“删除”)。

在我得到这一点之前,pre-req需要设置一个简单的VBA脚本来捕获删除事件。

我在MSDN上看了一下,发现下面的代码插入到“ThisOutlookSession”对象中。

Public WithEvents myItem As Outlook.MailItem 

Public Sub DeleteMail() 
Const strCancelEvent = "Application-defined or object-defined error" 
    On Error GoTo ErrHandler 
    Set myItem = Application.ActiveInspector.CurrentItem 
    myItem.Delete 
    Exit Sub 

ErrHandler: 
    MsgBox Err.Description 
    If Err.Description = strCancelEvent Then 
    MsgBox "The event was cancelled." 
    End If 
    'If you want to execute the next instruction 
    Resume Next 
    'Otherwise it will finish here 
End Sub 

Private Sub myItem_BeforeDelete(ByVal Item As Object, Cancel As Boolean) 
    'Prompts the user before deleting an item 
    Dim strPrompt As String 
    'Prompt the user for a response 
    strPrompt = "Are you sure you want to delete the item?" 
    If MsgBox(strPrompt, vbYesNo + vbQuestion) = vbNo Then 
    'Don't delete the item 
    Cancel = True 
    End If 
End Sub 

但是,这不会运行。当我去删除一个项目时(通过点击收件箱中的“del”键或打开项目并点击功能区上的“删除”),项目移动到已删除邮件文件夹,但我没有看到消息框。这似乎相对简单,我不确定我错过了什么。

+0

什么导致DeleteMail子文件运行?如果没有,myItem从不初始化。 –

回答

1

看起来像BeforeDelete事件是有限的使用,用DeleteMail代码实现。

根据此https://msdn.microsoft.com/en-us/library/office/ff861266.aspx“应在Outlook可以调用事件过程之前调用DeleteMail()过程”。

因此,您的操作“...通过点击收件箱中的”del“键或打开项目并单击”功能区上的“删除”无效。

您可以调查NewInspector事件,以在打开项目和浏览器的SelectionChange事件时设置myItem。

你应该可以在Deleted文件夹上使用ItemAdd https://msdn.microsoft.com/en-us/library/office/ff869609.aspx做你想做的。

+0

谢谢!尽管这并不完美,但我可以在已删除的项目文件夹中挂入itemadd事件,以创建mailitem的副本,因为它被“删除”。 – DNadel