Hi Everyone,

I need my application to loop through all unread items and action depending who send the email. This I can do with no issues. The problem I'm having is when I mark the message as read the Items Count decreased in real time.

Here is my full code:

        Dim objOutlook As Outlook.Application
        Dim outlookNameSpace As Outlook.NameSpace
        Dim x As Integer
        Dim filename As String = ""

        objOutlook = New Outlook.Application()
        outlookNameSpace = objOutlook.GetNamespace("MAPI")

        Dim oInbox As Outlook.MAPIFolder
        oInbox = objOutlook.GetNamespace("MAPI").GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox)

        Dim oItems As Outlook.Items = oInbox.Items
        oItems = oItems.Restrict("[Unread] = true")

        Dim oMsg As Outlook.MailItem

        For x = 1 To oItems.Count
            oMsg = oItems.Item(x)

            If oMsg.SenderEmailAddress = "someone@somecompany.com" Then
                Dim objAttachment As Outlook.Attachment
                For Each objAttachment In oMsg.Attachments
                    If objAttachment.FileName.Contains("TFTransReport") Then
                        filename = "C:\Temp\Imports\" + objAttachment.FileName
                        objAttachment.SaveAsFile(filename)
                        ReadImportFormFile(filename, conn)
                    End If
                Next objAttachment
                oMsg.UnRead = False
            End If
        Next x

For example I have 2 unrread messages so oItems.Count = 2. Only one of those messages needs to be actioned because its from someone@somecompany.com, I save the attachment and process it within the ReadImportFormFile Method. Once finished I mark the message as Read and move on to the next unread message but oItems.Count has changed to 1 and when I step into oMsg = oItems.Item(x) I get a an error "Array index out of bounds." I can see why I'm getting the error but I'm stuck on how to evaluate message number 2.

Any help appricated.

Regards,
Darren

Have you thought of scanning ("for nexting") in reverse order? I.o For x = 1 To oItems.Countyou would go For x = oItems.Count to 1 skip -1
Another approach would be to use for each item as outlook.item in oItems If you ask me, the latter would be the right one.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.