Outlook脚本通过规则删除附件

时间:2014-03-04 18:32:27

标签: vba outlook-vba outlook-2010

我是VBA和本论坛的新手。首先让我说我花了相当多的时间试图通过做和搜索来找到答案。

我需要创建一个脚本,我可以添加到我的规则中以删除某些电子邮件中的附件。我发现这个代码并认为它​​会有所帮助。

Public Sub deleteAttach(itm As Outlook.MailItem) 
Dim objAtt As Outlook.Attachment 
Set objAtt = itm.Attachments
objAtt.itm(1).Delete
End Sub

现在我似乎无法使这段代码正常工作。阅读之后,我意识到itm需要成为一个对象,但不知怎的,如果我使用Public Sub deleteAttach(ByVal Item As Object)该规则找不到我的脚本。

我还尝试将代码更改为objATT.Delete

任何帮助将不胜感激。谢谢。

3 个答案:

答案 0 :(得分:0)

你确定它缺少子程序吗?当数组从索引0开始时,它被设置为第2项

Public Sub deleteAttach(itm As Outlook.MailItem) 
'Dim objAtt As Outlook.Attachment 
'Set objAtt = itm.Attachments 'AttachmentS collection
'objAtt.itm(0).Delete 'note the 0 starts the indexing
'or
'for each att in objAtt
'   att.Delete
'next
For j = itm.Attachments.Count To 1 Step -1
        itm.Attachments.Remove (j)
Next j
itm.Save  'Save the mail item without attachments
End Sub

答案 1 :(得分:0)

您的代码永远不会正在阅读项目的已删除附件。你关闭了附件,但忘记再次“设置它”。

此外,您需要在代码顶部使用Option Explicit

Public Sub deleteAttach(itm As Outlook.MailItem) 
Dim objAtt As Outlook.Attachment 
Set objAtt = itm.Attachments 'this creates a "new" attachment you then delete from
objAtt.itm(1).Delete 'This line makes no sense if you think about it
End Sub

尝试以下方法:

Public Sub deleteAttach(itm As Outlook.MailItem) 
    itm.Attachments(1).Delete
    itm.Save    
End Sub

如果您不习惯在以编程方式修改电子邮件后执行“保存”,则会遇到类似于此的模糊Outlook问题。

或者,如果您想要删除所有附件,您可以在列表中向后迭代:

Public Sub deleteAttach(itm As Outlook.MailItem)
    dim i as integer
    for i = ubound(itm.Attachments) to lbound(itm.Attachments)
        itm.Attachments(i).Delete
    next i
    itm.Save    
End Sub

答案 2 :(得分:0)

打开您认为规则应处理的项目并运行deleteAttach_test。

Private Sub deleteAttach_test()
    Dim currItem As mailitem
    Set currItem = ActiveInspector.currentItem
    deleteAttach currItem
End Sub

Public Sub deleteAttach(itm As Outlook.mailitem)
    ' There is only one attachment in the mail
    itm.Attachments(1).Delete
    itm.Save
End Sub

回复:“规则找不到我的脚本。”

在向规则添加“RunAScript”时选择脚本。如果邮件是调用规则的邮件,则代码必须运行。


如果可以有多个附件:

Private Sub deleteAttach_V1_test()
    Dim currItem As mailitem
    Set currItem = ActiveInspector.currentItem
    deleteAttach_V1 currItem
End Sub

Public Sub deleteAttach_V1(itm As Outlook.mailitem)
    Dim j As Long

    ' Delete in reverse, the highest numbered remaining item each time
    For j = itm.Attachments.count To 1 Step -1
       itm.Attachments(j).Delete   
    Next j
    itm.Save
End Sub

Private Sub deleteAttach_V2_test()
    Dim currItem As mailitem
    Set currItem = ActiveInspector.currentItem
    deleteAttach_V2 currItem
End Sub

Public Sub deleteAttach_V2(itm As Outlook.mailitem)
    Dim i As Long

    For i = 1 To itm.Attachments.count
        ' Delete the new first item each time
        itm.Attachments(1).Delete   
    Next i
    itm.Save
End Sub