Search code examples
excelvbaoutlookoutlook-filter

DSAL query for Unread mail in the filter for Outlook using Inbox.Items.Restrict


I am writing a code for automatically downloading an attachment from unread mail containing several keywords in the subject for example "training" but when I tried using SQL query for unread mail, it's giving me an error.

  Filter = "@SQL=" & Chr(34) & "urn:schemas:httpmail:subject" & _
               Chr(34) & " Like '%Training%' AND " & _
               Chr(34) & "urn:schemas:httpmail:hasattachment" & _
               Chr(34) & "=1"
  Set Items = Inbox.Items.Restrict(Filter) 'No error while running this code

 Filter = "@SQL=" & Chr(34) & "& Chr(34) & "urn:schemas:httpmail:subject" & _
               Chr(34) & " Like '%Training%' AND" & _
                    Chr(34) & "urn:schemas:httpmail:hasattachment" & _
                    Chr(34) & "= 1" & Chr(34) & "AND" & _
                    Chr(34) & "urn:schemas:httpmail:read" & _
                    Chr(34) & "= 0"


Set Items = Inbox.Items.Restrict(Filter) 
' Now here it is giving me runtime error '-2147352567(800200009)'

All the help will be appreciated. Thanks in Advance


Solution

  • You almost got it,

    The Error is coming from here Chr(34) & "= 1" & Chr(34) & "AND" & _

    It Should be Chr(34) & "=1 AND " & _


    Example

    Filter = "@SQL=" & Chr(34) & "urn:schemas:httpmail:subject" & _
                       Chr(34) & " Like '%Training%' AND " & _
                       Chr(34) & "urn:schemas:httpmail:hasattachment" & _
                       Chr(34) & "=1 AND " & _
                       Chr(34) & "urn:schemas:httpmail:read" & _
                       Chr(34) & "=0"
    

    Filtering Items Using a String Comparison that DASL filters support includes equivalence, prefix, phrase, and substring matching. Note that when you filter on the Subject property, prefixes such as "RE: " and "FW: " are ignored.