bneigher
bneigher

Reputation: 848

Use Folder Path String to select folder in VBA in Outlook

How can I enter a string as a folder location ex. \MySpecificEmailAddress\Inbox To select that folder in VBA using outlook? I obtained the path using:

... = ActiveExplorer.CurrentFolder.FolderPath

I have searched far and wide to automatically tell the script which specific folder to run a macro on without having to select the folder then run the script.

Upvotes: 0

Views: 14130

Answers (2)

Srikanth
Srikanth

Reputation: 1

I have just now built and tested the following function to get an outlook folder by it's path string... of course it is in Javascript, but you can easily convert it to VBA or VBScript.

function getFolderByPath(oParent, sFoldPath) {
    sFoldPath = sFoldPath.toLowerCase();
    var oFolds = new Enumerator(oParent.Folders);
    for(oFolds.moveFirst(); !oFolds.atEnd(); oFolds.moveNext()) {
        var sPath = oFolds.item().FolderPath.toLowerCase();
        if(sPath == sFoldPath) return oFolds.item();
        if(sFoldPath.indexOf(sPath + "\\") == 0) return getFolderByPath(oFolds.item(), sFoldPath);
    }
    return null;
}

Usage:

var oRequiredFolder = getFolderByPath(oNameSpaceObject, "\\\\My\\required\\folder\\path");

Hope this helps someone.

Upvotes: 0

SliverNinja - MSFT
SliverNinja - MSFT

Reputation: 31651

You should be able to enumerate Session.Stores and then Store.GetRootFolder.Folders to access all folders for a given mailbox. Depending on how many levels deep you need to go, this may take a bit more effort (i.e. recursion).

Here is a code snippet from MSDN which enumerates all folders under the mailbox/store root folders:

Sub EnumerateFoldersInStores()  
 Dim colStores As Outlook.Stores 
 Dim oStore As Outlook.Store 
 Dim oRoot As Outlook.Folder 

 On Error Resume Next 

 Set colStores = Application.Session.Stores  
 For Each oStore In colStores 
   Set oRoot = oStore.GetRootFolder 
   Debug.Print (oRoot.FolderPath) 
   EnumerateFolders oRoot 
 Next 

End Sub 

Private Sub EnumerateFolders(ByVal oFolder As Outlook.Folder) 
 Dim folders As Outlook.folders 
 Dim Folder As Outlook.Folder 
 Dim foldercount As Integer 

 On Error Resume Next 
 Set folders = oFolder.folders 
 foldercount = folders.Count 
 'Check if there are any folders below oFolder 
  If foldercount Then 
    For Each Folder In folders 
      Debug.Print (Folder.FolderPath) 
      EnumerateFolders Folder 
    Next 
 End If 
End Sub

Upvotes: 2

Related Questions