none
Cannot Loop through Results Items RRS feed

  • Question

  • Hi All,

    I have an issue when looping through the items of a Results object.

    • when I step into the code (debug F8) the xResults is read properly, collection sCol is filled
    • When I execute the code (debug F5), xResults is not read. As a result, collection sCol is NOT filled. The code cannot even read xResults.Count

    Note:

    I have tried:

    • Different loops: For , While , Do Until
    • I tried to set zResults = CVar(xResutls)

    I am running Outlook 365 MSO (16.0.11328.20478).

    Request:

    • Please explain if I am doing something wrong, or if you understand why the Results object behaves this way
    • Please suggest a workaround / alternative solution if possible

    Sub MarkCompletedMailsAsRead()
        Dim xMailBox As MAPIFolder
        Dim xNS As NameSpace: Set xNS = Outlook.GetNamespace("MAPI")
        Dim xDefaultStore As String
        Dim xSearch As Search
        Dim sScope As String
        Dim sFilter As String
        Dim sCol As New Collection
        Dim xResults As Results
        
        'DETERMINE SCOPE OF SEARCH
        xDefaultStore = Outlook.Application.GetNamespace("MAPI").DefaultStore.DisplayName
        For Each Folder In xNS.folders
            If Folder.Name = xDefaultStore Then
                Set xMailBox = Folder
                Exit For
            End If
        Next
        For Each xFolder In xMailBox.folders
            sScope = sScope & "'" & xFolder.Name & "'" & ","
        Next
        If Right(sScope, 1) = "," Then
            sScope = Mid(sScope, 1, Len(sScope) - 1)
        End If
            
        'DETERMINE FILTER
        sFilter = "http://schemas.microsoft.com/mapi/proptag/0x10900003 = " & olFlagComplete & _
                  " AND " & "urn:schemas:httpmail:read = 0"
        
        'GET SEARCH RESULTS
        Set xSearch = Application.AdvancedSearch(Scope:=sScope, Filter:=sFilter, SearchSubFolders:=True)
        Set xResults = xSearch.Results
        
        Dim j As Integer: j = xResults.Count
        For Each Y In xResults
            Set Y = xResults.GetNext
            sCol.Add Y
        Next
        
        'UPDATE ITEMS IN SCOPE
        For Each c In sCol
            c.UnRead = False
            c.Save
        Next
    End Sub

    Thursday, January 9, 2020 11:54 AM

All replies