none
Outlook VBA Incorrectly Replying to Emails in Folder RRS feed

  • Question

  •  I intended for the following code to reply all emails under "sent items" folder.

    Function ReplyEmail()
        
        Dim olMail
        Dim olMails
    
        Set olApp = CreateObject("Outlook.Application")
        
        Set olNs = olApp.GetNamespace("MAPI")
        Set olSFolder = olNs.GetDefaultFolder(olFolderSentMail)
        Set olMails = olSFolder.Items
        
        MsgBox (olMails.Count)
        
    '    For i = 1 To olMails.Count
    '
    '        olMails(i).ReplyAll
    '        olMails(i).Importance = 2
    '        olMails(i).Send
    '
    '    Next i
        
        For Each olMail In olMails
    
            olMail.ReplyAll
            olMail.Importance = 2
            olMail.Send
    
    
        Next olMail
    
    
    End Function

    However, for some strange reason, this function sends only half of all emails in designated folder. If there are 9 emails, the function sends out 5 (4 left), then if I run another iteration, the function sends out 3, and so on...

    If I change olMail.Send to olMail.Display, then the function displays all emails in pop-up frames.

    If I run the for loop that's commented out, I get an array index out of range error halfway through the process. This problem only occurs when I insert olMail.Send as if this command skips half of the emails.

    Has any one encountered this issue or know what's the reason behind it?

    Thanks.


    Wednesday, June 14, 2017 2:34 AM

All replies

  • The act of sending mail will create new items in the Sent Items folder which will change the Items collection.

    Instead of referencing olMails.Count in the loop, first save olMails.Count to a variable and use that in your loop so that the iterations are not affected by changes to the Items collection.

    Wednesday, June 14, 2017 11:16 AM
  • Hello,

    You need to send the reply mailitem instead.

    E.g.

    Dim reMail As MailItem
    For i = 1 To olMails.Count
    Set reMail = olMails(i).ReplyAll
    reMail.Send
    Next I

    Regards,

    Celeste


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, June 15, 2017 7:18 AM
    Moderator