For Each loop: Just deletes the very first attachment

前端 未结 2 1357
独厮守ぢ
独厮守ぢ 2021-01-28 06:47

I\'ve been trying to delete the attachments in Outlook after copying them using for each loop. It just deletes the very first attachment after copying it but does not go for the

相关标签:
2条回答
  • 2021-01-28 07:39

    Try this. I added code/comments to iterate through and remove all the attachments after you do your saving. The reasons you should do this are explained very well here by David Zemens.

    You also should get in the habit of saving messages you modify in Outlook VBA as sometimes this is important, sometimes it's not, but it can confuse the heck out of you if you don't use Save when you need to.

     'location to save in.  Can be root drive or mapped network drive.
        Const attPath As String = "C:\Users\pkshahbazi\Documents\EmailAttachments\"
        Set myAttachments = Msg.Attachments
            For Each olAttch In myAttachments
                Att = olAttch.DisplayName
                If Right(olAttch.FileName, 3) = "zip" Then
                olAttch.SaveAsFile attPath & Att
                'olAttch.Delete
                End If
            Next olAttch
            'iterate through all attachments, going backwards
            dim j as integer
            For j = Msg.Attachments.Count To 1 Step -1
                Msg.Attachments.Remove (j)
            Next j
    
            'make sure to save your message after this
            Msg.save
        Msg.UnRead = False
    
    
    
    
    End If
    
    0 讨论(0)
  • 2021-01-28 07:46

    In your previous question we changed from an indexed loop to a non-indexed loop, because you did not have any .Delete requirement. Unfortunately, deleting items from a collection requires an indexed iteration.

    This is because, when you have 3 items:

    • Item 1 = Attachment 1
    • Item 2 = Attachment 2
    • Item 3 = Attachment 3

    Then when you delete the first item (Item 1/Attachment 1), it takes you to item 2, but when the delete happens, you are left with the collection that looks like:

    • Item 1 = Attachment 2
    • Item 2 = Attachment 3

    So your loop will delete items 1 and 3, but it will never touch item 2.

    The simplest way to fix this for you, without using an indexed loop and re-writing your script, is to just add another loop to do the delete method.

    @Enderland provides the example for this. I will not duplicate his effort, but I did want to explain what is happening for you. This is always the case when deleting items from a collection, you have to step through the collection in reverse order.

    0 讨论(0)
提交回复
热议问题