2016-12-08 77 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