More Outlook Resource Sites

Microsoft Developer Network (MSDN)

FAQs and other general resources

share code 20-Mar-2019 12:36

Looking for help with Outlook programming projects — VSTO, add-ins, VBA, custom Outlook forms, etc.? You′ve come to the right place!

NEW! >> Subscribe to this site via RSS. For more RSS options, see the complete list of feeds on our main news page.

Code level: beginner    Code area: Basic Outlook Printer Friendly Version
Title: GetFolderByName
Description: Returns a MAPIFolder object based on the name of the folder (without knowing the path)
Date: 14-Jul-2004  17:19
Code level: beginner
Code area: Basic Outlook
Posted by: rockman
This message is displayed as VB.NET
 '=============================================================
' GetFolderByName
' By: Jeff Rockow
'-------------------------------------------------------------
' Purpose: Search the folder tree to get any folder, based on
'          its name alone
'-------------------------------------------------------------
' Arguments: strFolderName = name of folder to search for
'-------------------------------------------------------------
' Returns: MAPIFolder object if folder exists and is unique,
'          otherwise Nothing
'
'          intFolderCount is also accessible
'=============================================================
Public Function GetFolderByName(strFolderName As String, Optional objFolder As Outlook.MAPIFolder, Optional intFolderCount) As MAPIFolder
Dim objApp As Outlook.Application
Dim objNS As Outlook.NameSpace
Dim colStores As Outlook.Folders
Dim objStore As Outlook.MAPIFolder
Dim colFolders As Outlook.Folders
Dim objResult As Outlook.MAPIFolder
Dim I As Long

On Error Resume Next
  Set objApp = CreateObject("Outlook.Application")
  Set objNS = objApp.GetNamespace("MAPI")
  Set colStores = objNS.Folders
  
  If objFolder Is Nothing Then
    'If objFolder is not passed, assume this is the initial call and cycle through stores
    intFolderCount = 0
    For Each objStore In colStores
      Set objResult = GetFolderByName(strFolderName, objStore, intFolderCount)
      If Not objResult Is Nothing Then Set GetFolderByName = objResult
    Next
  Else
    'Test to see if this folder's name matches the search criteria
    If objFolder.Name = strFolderName Then
      Set GetFolderByName = objFolder
      intFolderCount = intFolderCount + 1
    End If
    Set colFolders = objFolder.Folders
    'Cycle through the sub folders with recursive calls to this function
    For Each objFolder In colFolders
      Set objResult = GetFolderByName(strFolderName, objFolder, intFolderCount)
      If Not objResult Is Nothing Then Set GetFolderByName = objResult
    Next
  End If
  'If two or more folders exist with the same name, set the function to Nothing
  If intFolderCount > 1 Then Set GetFolderByName = Nothing
  
  Set objResult = Nothing
  Set colFolders = Nothing
  Set objNS = Nothing
  Set objApp = Nothing
End Function
All 23comments
Page [ 1 2 3 Next >>  
  15-Jul-2004  00:25   
Use the following code behind a button to test the above code:

Private Sub cmdTestCode_Click()
Dim objFolder As Outlook.MAPIFolder
Dim intFolderCount As Integer
Dim sFolderFind As String
Dim sFolderName As String

  sFolderFind = InputBox("Enter the name of the folder to find:", "GetFolderByName")
  Set objFolder = GetFolderByName(sFolderFind, , intFolderCount)
  If Not objFolder Is Nothing Then sFolderName = objFolder.Name
  MsgBox "Folder Name: " & sFolderName & String(2, vbCrLf) & "Folder Count: " & intFolderCount
End Sub
  20-Jan-2005  13:54   
What is this searching for? How should this be used? I do not see an area to specify the folder name I am looking for.
  20-Jan-2005  14:37   
Stanley,
In Outlook it is neccessary to have an object variable (objFolder in the above example) in order to perform various tasks on the contents of that object.

The standard GetFolder function that you find on this web site and in Sue's book requires that you know the exact path to the Folder in question (e.g. \Personal Folders\Job 1\Programming\Gopher). If you or someone else choose to move the Gopher Folder to another location, your "hard wired" code will fail.

The GetFolderByName function is more forgiving in that you pass it the folder name (by the first parameter of the function: in the example its the sFolderFind variable) and it goes searching for the folder and returns an object variable referencing that Folder.

The limitations for this routine include the fact that the folder name must be unique. Obviously, if there are TWO folders named "Gopher" then the routine doesn't know which "Gopher" folder you want. You can check for this possibility as the function returns a variable (intFolderCount) containing how many folders it found with the specificied name.

Hope this answers some of your questions,
Jeff
  27-Jan-2005  16:53   
Hi, I am looking the same code in vbscript. Can anybody please convert this for me?
  28-Jan-2005  09:51   
You should be able to convert it yourself simply by removing the typing (e.g. As String) from the variable declarations and taking out the Optional keywords.
  28-Jan-2005  15:47   
Ok, I tried it and it doesn't work. I think the problem is that the folder that I am looking for is not a default folder. here is the path looks like "\Personal Folders\ACD Hangup Data" . My code works if I use "myNameSpace.PickFolder".. Please suggest.
  31-Jan-2005  10:00   
Parvez, you're using the wrong function. If you know the full path, you an use the GetFolder() function http://www.outlookcode.com/d/code/getfolder.htm . Jeff's function on this page is designed to find a folder based solely on the folder name, not the path. It fails when you give it a path such as "\Personal Folders\ACD Hangup Data" because it's not designed to parse a path.
 
  13-Feb-2005  20:43   
Sue,

I tried implementing Jeff Rockow’s folder search in C# ,NET and ran into this error when I entered: foreach (myo o in outlookNS.Folders)
D:\als_work\C# Development\StringTesting\Class1.cs(65): foreach statement cannot operate on variables of type 'Outlook.Folders' because 'Outlook.Folders' does not contain a definition for 'GetEnumerator', or it is inaccessible

So I wrote the following in C# .NET (I’m working with Outlook 2002) is there an enumerator somewhere?
public static MAPIFolder getFolderByName(string name, NameSpace outlookNS)
        {
            MAPIFolder folder = null;

            for (int i = 1; i <= outlookNS.Folders.Count; i++) {
                folder = outlookNS.Folders.Item(i);
                if (outlookNS.Folders.Item(i).Name == name)
                    return folder;
                else
                    if (outlookNS.Folders.Count > 1) {
                        folder = getFolderByName(name, folder);
                        if (folder != null && folder.Name == name)
                            return folder;
                    }
            }
            return null;
        }

        public static MAPIFolder getFolderByName(string name, MAPIFolder folder)
        {
            MAPIFolder myFolder;

            for (int i = 1; i <= folder.Folders.Count; i++) {
                myFolder = folder.Folders.Item(i);
                if (myFolder.Name == name)
                    return myFolder;
                else
                    if (myFolder.Folders.Count > 1) {
                    folder = getFolderByName(name, myFolder);
                    if (folder != null && folder.Name == name)
                        return folder;
                }
            }
            return null;
        }


Thanks...
Austin
 
  03-Mar-2005  14:19   
Sue or Jeff,

I am using Jeff's getfolderbyname function to move items from my inbox to .pst subfolders. It works well on my system at home, but at work the function "hangs" for about two minutes before returning the folder (I am on an exchange server network, with many more .pst folders than at home). I thought it might speed things up if I passed the optional folder object argument, but I'm not sure how to do that. Any suggestions?

Thanks,
Shawn
  04-Mar-2005  10:54   
Shawn,

Interesting question that you have there. The optional folder object argument is used by the function itself for the "recursive" manner in which it searches through the folders, however, it makes sense (I think) that you could "prime-the-pump" as it were if your folder layout is composed of nested folders (it would not benefit a flat one-dimensional folder layout). By sending it an initial folder object you could in essence tell the function "I know the folder I'm looking for is in this branch of my folder layout". I haven't tried it but it seems that it would work. To pass the folder object, first create the forder object using Sue's GetFolder routine, and then pass that variable as the second argument of the function.

I'm not sure that it will solve your speed problem however. The computer should be able to search through 100's of folders in a split second. If your performance deterioration is due to very slow network traffic, then yes I guess it may help.

Let me know what you find out.

Cheers,
Jeff
Page [ 1 2 3 Next >>