'Using VBA in Outlook to Move Emails Containing Name of a Folder
I am looking for some pointers for a VBA code for Outlook. Specifically, run this code to clean up my inbox.
We manually create a new folder each time we get a new client. I'd like this code to scan through list of existing client folders in Outlook, if an email contains keywords that matches the name of the folder, then move email to said folder.
E.g. something like if email in inbox contains keyword "Apple", and if "Apple" folder exists, then move email to "Apple" folder. Else nothing.
Similarly, if email in inbox contains keyword "Google", and if "Google" folder exists, then move email to "Google" folder. Else nothing.
Without having to set rules for each new folder that is created.
Is this even possible? Any advice would be appreciated, can't seem to find a sample code for this.
Thanks!
Solution 1:[1]
Yes, it is possible. In VBA you can scan all folders for email with a specific keyword and if a corresponding folder exists in Outlook you could move it to that folder. Let's consider what needs to be done for that. First, you need to scan all folders. The AdvancedSearch method of the Application class allows to perform a search based on a specified DAV Searching and Locating (DASL) search string. The key benefits of using the AdvancedSearch
method in Outlook are:
- The search is performed in another thread. You don’t need to run another thread manually since the
AdvancedSearch
method runs it automatically in the background. - Possibility to search for any item types: mail, appointment, calendar, notes etc. in any location, i.e. beyond the scope of a certain folder. The Restrict and
Find
/FindNext
methods can be applied to a particularItems
collection (see theItems
property of theFolder
class in Outlook). - Full support for DASL queries (custom properties can be used for searching too). To improve the search performance, Instant Search keywords can be used if Instant Search is enabled for the store (see the
IsInstantSearchEnabled
property of theStore
class). - You can stop the search process at any moment using the
Stop
method of theSearch
class.
Read more about that in the Advanced search in Outlook programmatically: C#, VB.NET article.
So, you could run a search for items in the background and then at some point when the search is completed you may be notified.
To find the target folder you could iterate over all folders in Outlook recursively. See Enumerate folders for more information on that.
Finally, to move items you can use the Move method which moves a Microsoft Outlook item to a new folder.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Eugene Astafiev |