Purge Folders on Demand


Outlook VBA on Demand

Gordon Filby, a reader from Germany, wants to build an Outlook VBA macro that deletes all the items from several folders. He says his list of folders won't change often. However, I want to be able to modify the list of purged folders without needing to update the code. My solution is to use a Microsoft Outlook folder to hold the folder list. This Outlook folder will contain one item for each purged folder.

First, create a folder to hold Mail items. This folder can reside in an Exchange Server Public Folders hierarchy or in your personal mailbox or folders. The sample code in Listing 1 uses a folder named Folders to Purge in a Personal Folders file named VBA Data. You need to provide the path to the folder in the section of Listing 1 marked #### User Options ####.

In this folder, create a post for each folder that you want to purge. The subject of the post must be the full path to the folder (e.g., "Public Folders/All Public Folders/My Folders/My List").

Listing 1's CleanFolders subroutine uses the GetMAPIFolder() function, which you've seen in previous Outlook VBA on Demand columns. This function takes as its argument the full path to an Outlook folder and returns a MAPIFolder object. (Because this function is basic to Outlook programming, I haven't included it here. You can obtain the function, along with the other procedures, from my past columns on the Windows 2000 Magazine Web site.) Using the value set in the code for the strFoldersPurged variable, the CleanFolders procedure first employs the GetMAPIFolder() function to obtain the folder that holds the names of the folders you want to purge. Then, using the path set in the item's Subject property, the procedure loops through the items in that folder and uses the GetMAPIFolder() function again to obtain each folder you want to purge. If you don't provide a valid path, the CleanFolders routine simply ignores that folder.

After CleanFolders obtains a folder to be purged, the subroutine passes the folder to the PurgeFolder() function, which you see in Listing 2. The heart of the PurgeFolder() function is a Do loop that uses the GetFirst, GetNext, and Delete methods to delete each item in the folder and keep a running count. The PurgeFolder() function returns a string, which CleanFolders uses to build a message box that reports to the user how many items the program removed from which folders.

Notice the syntax of the CleanFolders procedure's MsgBox statements. Prompt and Title are named arguments. When a method includes named arguments, you can make your code more readable by using the arg:= syntax to label each argument. This capability is particularly helpful when you're working with complex strings.

Hide comments


  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.