Using the .Restrict method in Outlook VBA to filter on single recipient email address

Jaspos picture Jaspos · Apr 29, 2013 · Viewed 12.4k times · Source

I have code in Access that gets all emails in the user's Inbox that are sent by an individual email address. This code (simplified, below) works fine:

Dim outItems as Outlook.Items
Dim strEMAddress as string
Dim outFolder as Outlook.MAPIFolder

Set outFolder = outNS.GetDefaultFolder(olFolderInbox)
Set outItems = outFolder.Items

str="[email protected]"

Set outItems = outItems.Restrict("[SenderEmailAddress] = " & "'" & strEMAddress & "'")

I am looking for something that will do likewise on the SentMails folder, restricting the items to those sent to a specific email address.

I know this is complicated by the fact that .Recipients is a collection (as items can/do have more than one recipient). I am hoping there is a way to return a list of items that contain the email address I am looking for in any of the sent fields (To/CC/bcc - but happy with just To if this is easier).

I have searched online and found .To is no good (is not the email address) and I can't get pseudo code such as this work:

 Set outItems = outItems.Restrict("[Recipients] = " & "'" & strEMAddress & "'")

Answer

S.aad picture S.aad · Apr 25, 2015

You can use the DASL query as the filter string in your items.restrict method.

For example to find all mails i sent to Ali Raza i use the following

str_fltr = "@SQL=""urn:schemas:httpmail:displayto"" ci_phrasematch '%Ali Raza%'"

The good thing about the above DASL query is that it returns matches with multiple recepients whether if you use the jet syntax for searching resultx will only contain items with one recipient. Jet syntax is the one that you are currently using. You should use the [To] property rather than [Recipients]

Here https://msdn.microsoft.com/en-us/library/cc513841%28v=office.12%29.aspx#SearchingOutlookData_Overview is good place where you can learn almost everything about searching in outlook.

Here http://www.msoffice.us/Outlook/PDF/%28Outlook%202010%29%20Common%20DASL%20Property%20Tags.pdf is a list of common DASL tags which will come in handy if you get a grip on DASL syntax.