• Outlook User
  • New Outlook app
  • Outlook.com
  • Outlook Mac
  • Outlook & iCloud
  • Developer
  • Microsoft 365 Admin
    • Common Problems
    • Microsoft 365
    • Outlook BCM
    • Utilities & Addins

Use a Macro to Assign Messages in a Shared Mailbox

Slipstick Systems

› Developer › Code Samples › Use a Macro to Assign Messages in a Shared Mailbox

Last reviewed on July 26, 2021     48 Comments

Many organizations use shared Exchange mailboxes for support and general information email addresses and assign the responsibility to answer the inquiries to a small group of users. To help even the workload, some managers want to assign the messages to users as they arrive, round-robin style, so each user gets the same number of messages.

assign messages to people

It's actually fairly easy to do: count the messages and use Select Case to assign a message to a person.

In these examples, I'm using an ItemAdd macro because it can watch any folder in your profile for new messages, whereas a rule only watches your account's Inbox. Outlook needs to be open to use a macro and if you are moving messages to folders in other mailboxes, the mailboxes need to be in your profile (as a shared mailbox is fine). Because the Inbox is not the default Inbox in your profile, you'll need to use the GetFolderPath macro at the end of this page.

These macros start when Outlook starts; to kickstart the macros during testing, click in the Application_Startup macro and click Run.

To watch a folder in the default mailbox in a profile, use the following line in the Application Startup macro.
Set olInboxItems = objNS.GetDefaultFolder(olFolderInbox).Items

Step 1

At the top of ThisOutlookSession, add this code and add the GetFolderPath function (found at the end of this article) to a new Module. Note: if you are watching for new messages in your default mailbox and are not moving the messages to folders in another mailbox or data file, you don't need the GetFolderPath function.

Dim i As Long
Private WithEvents olInboxItems As Items
 
Private Sub Application_Startup()
  Dim objNS As NameSpace
  Set objNS = Application.Session
  Set olInboxItems = GetFolderPath("Shared mailbox name\Inbox").Items
Set objNS = Nothing
End Sub

Step 2

Next, copy one of the ItemAdd macros below and paste it under the End Sub line in the Application_Startup macro.

Assign Categories | Move Messages to Folders
Move Messages to Other Mailboxes | Forward Messages

 

Assign Categories "Round Robin" style

Use the name of the mailbox as it appears in your folder list.

Private Sub olInboxItems_ItemAdd(ByVal Item As Object)
    Dim strCat As String
    
    If Item.Class = olMail Then
     
    Select Case i
     Case 0
          strCat = "Case 0"
     Case 1
          strCat = "Case 1"
     Case 2
          strCat = "Case 2"
     Case 3
          strCat = "Case 3"
     Case 4
          strCat = "Case 4"
    End Select
        
    Item.categories = strCat
            Item.Save
        Err.Clear
     End If
     i = i + 1
     Debug.Print i
     If i = 5 Then i = 0
 End Sub

 

Move Messages to Folders

In this example, I'm moving messages to a folder in the mailbox that is under the Inbox. (The messages in this screenshot were assigned the Case 0 category using the previous macro.)

Sort messages to folders

If the folder is at the same level as the Inbox, use this line instead:
Set objDestFolder = Session.GetDefaultFolder(olFolderInbox).Parent.Folders(moveFolder)

Private Sub olInboxItems_ItemAdd(ByVal Item As Object)

    Dim objDestFolder As Outlook.MAPIFolder
    Dim moveFolder As String
    
    If Item.Class = olMail Then
     
    Select Case i
     Case 0
          moveFolder = "Folder01"
     Case 1
          moveFolder = "Folder05"
     Case 2
          moveFolder = "Folder10"
     Case 3
          moveFolder = "Folder12"
     Case 4
          moveFolder = "Folder14"
    End Select
    
Set objDestFolder = Session.GetDefaultFolder(olFolderInbox).Folders(moveFolder)
  Item.Move objDestFolder
        End If
        
        Err.Clear
          
     i = i + 1
     Debug.Print i
     If i = 5 Then i = 0
 Set objDestFolder = Nothing
 End Sub

 

Move messages based on sender name

The modification is in response to the question in this Microsoft Community thread, Microsoft Community thread, where the messages are assigned by the sender's name.

We need to get the first letter of the sender's name. The select case statements check to see which case is true and moves the message to a folder. The Case Else handles all messages that do not match the other case statements.

I'm using UCase function to force capitalize the letters, otherwise, someone with a lowercase display name would end up in the Else folder. If you prefer, you can force the sender names to lower case using Left(LCase(Item.SenderName), 1), but must also enter the letters in each case statement in lower case.

Private WithEvents olInboxItems As Items
 
Private Sub Application_Startup()
  Dim objNS As NameSpace
  Set objNS = Application.Session
  'Set olInboxItems = GetFolderPath("Shared mailbox name\Inbox").Items
  Set olInboxItems = objNS.GetDefaultFolder(olFolderInbox).Items
Set objNS = Nothing
End Sub

Sub olInboxItems_ItemAdd(ByVal Item As Object)

    Dim objDestFolder As Outlook.MAPIFolder
    Dim moveFolder As String
    
   If Item.Class = olMail Then
    
     Debug.Print Item.SenderName, Left(Item.SenderName, 1)
     
    Select Case Left(UCase(Item.SenderName), 1)
    
     Case "A", "B", "C"
          moveFolder = "Folder01"
     Case "D", "E", "F"
          moveFolder = "Folder02"
     Case "G", "H", "I"
          moveFolder = "Folder03"
     Case Else ' letters not listed above
          moveFolder = "Folder04"
     
    End Select
    
Set objDestFolder = Session.GetDefaultFolder(olFolderInbox).Folders(moveFolder)
  Item.Move objDestFolder
        End If
        
        Err.Clear
           
Set objDestFolder = Nothing
 End Sub

 

Move Messages to Other Mailboxes

In this example, I'm moving messages to each person's Inbox. To do this, I need the mailboxes in my profile as secondary mailboxes.

Private Sub olInboxItems_ItemAdd(ByVal Item As Object)

    Dim objDestFolder As Outlook.MAPIFolder
    Dim moveFolder As String
    
    If Item.Class = olMail Then
     
    Select Case i
     Case 0
          moveFolder = "Mary Contrary\Inbox"
     Case 1
          moveFolder = "Diane Poremsky\Inbox"
     Case 2
          moveFolder = "John Smith\Inbox"
     Case 3
          moveFolder = "Mark Jackson\Inbox"
     Case 4
          moveFolder = "Sue Ellen\Inbox"
    End Select

Set objDestFolder = GetFolderPath(moveFolder)
   Item.Move objDestFolder
        End If

        Err.Clear
          
     i = i + 1
     Debug.Print i
     If i = 5 Then i = 0
 Set objDestFolder = Nothing
 End Sub

 

Forward Messages

If you prefer to forward messages, you'll use this code. The address in the sendTo variable can either be the users Exchange alias or their SMTP email address. Change oForward.Display to oForward.Send to send the messages automatically.

Private Sub olInboxItems_ItemAdd(ByVal Item As Object)

    Dim sendTo As String
    Dim oForward As MailItem
    Dim recip As Recipient
    If Item.Class = olMail Then
     
    Select Case i
     Case 0
          sendTo = "billys"
     Case 1
          sendTo = "johnj"
     Case 2
          sendTo = "dianep"
     Case 3
          sendTo = "maryc"
     Case 4
          sendTo = "henryp@mydomain.com"
    End Select
    
    Set oForward = Item.Forward
    Set recip = oForward.recipients.Add(sendTo)
        recip.Resolve
        oForward.Display 'send

        End If
        
        Err.Clear
          
     i = i + 1
     Debug.Print i
     If i = 5 Then i = 0

  Set recip = nothing
 End Sub

 

GetFolderPath Function

You need to use this function if the mailbox you are watching or that you are moving messages into is not the default mailbox in the profile.

' Use the GetFolderPath function to find a folder in non-default mailboxes
Function GetFolderPath(ByVal FolderPath As String) As Outlook.folder
    Dim oFolder As Outlook.folder
    Dim FoldersArray As Variant
    Dim i As Integer
         
    On Error GoTo GetFolderPath_Error
    If Left(FolderPath, 2) = "\\" Then
        FolderPath = Right(FolderPath, Len(FolderPath) - 2)
    End If
    'Convert folderpath to array
    FoldersArray = Split(FolderPath, "\")
    Set oFolder = Application.Session.Folders.Item(FoldersArray(0))
    If Not oFolder Is Nothing Then
        For i = 1 To UBound(FoldersArray, 1)
            Dim SubFolders As Outlook.Folders
            Set SubFolders = oFolder.Folders
            Set oFolder = SubFolders.Item(FoldersArray(i))
            If oFolder Is Nothing Then
                Set GetFolderPath = Nothing
            End If
        Next
    End If
    'Return the oFolder
    Set GetFolderPath = oFolder
    Exit Function
         
GetFolderPath_Error:
    Set GetFolderPath = Nothing
    Exit Function
End Function

How to use these Macros

First: You will need macro security set to low during testing.

To check your macro security in Outlook 2010 or 2013, go to File, Options, Trust Center and open Trust Center Settings, and change the Macro Settings. In Outlook 2007 and older, it’s at Tools, Macro Security.

After you test the macro and see that it works, you can either leave macro security set to low or sign the macro.

Open the VBA Editor by pressing Alt+F11 on your keyboard.

To use the macro code in ThisOutlookSession:

  1. Expand Project1 and double click on ThisOutlookSession.
  2. Copy then paste the macro into ThisOutlookSession. (Click within the code, Select All using Ctrl+A, Ctrl+C to copy, Ctrl+V to paste.)
  3. Right-click on Project1 and choose New > Module
  4. Paste GetFolderPath in this Module

More information as well as screenshots are at How to use the VBA Editor

Use a Macro to Assign Messages in a Shared Mailbox was last modified: July 26th, 2021 by Diane Poremsky
Post Views: 120

Share this:

  • Share on Facebook (Opens in new window) Facebook
  • Share on X (Opens in new window) X
  • Share on Reddit (Opens in new window) Reddit
  • Share on Bluesky (Opens in new window) Bluesky
  • Share on Mastodon (Opens in new window) Mastodon
  • Email a link to a friend (Opens in new window) Email

Related Posts:

  • Use a VBA macro to monitor a folder in a secondary mailbox for new mes
    Monitor secondary mailbox folder for new messages
  • Macro to Move Aged Email Messages
  • Assign Categories to Messages using Contact Category
  • Macro to Move or Copy an Outlook message to another folder

About Diane Poremsky

A Microsoft Outlook Most Valuable Professional (MVP) since 1999, Diane is the author of several books, including Outlook 2013 Absolute Beginners Book. She also created video training CDs and online training classes for Microsoft Outlook. You can find her helping people online in Outlook Forums as well as in the Microsoft Answers and TechNet forums.

Comments

  1. Brett says

    March 29, 2021 at 5:44 pm

    Hey Diane,

    I know this is an old thread, but I was going to see if you could help me. I am using a large combination of your code in two shared inboxes i manage at my job. The issue i am running into is trying to combine multiple round robin statements. So if the subject line has the word "Withdrawal" in it, then assign it to these three people. If the subject has the word deposit in it, assign it to these three people. The issue i am running into is in the below code, when it sees an e-mail with the subject "Withdrawal" it assigns it round robin correctly, but then the one below it, "Deposit" it always assigns it to the first person and the counter does not increase. I have tried everything and can not figure out how to make both counters work. Is there any insight you can give me?

    If InStr(1, UCase(Item.Subject), UCase("Withdrawal")) Or InStr(1, UCase(Item.Body), UCase("Withdrawal")) <> 0 Then
       Select Case a
       Case 0
         strCat = "Case 0"
       Case 1
         strCat = "Case 1"
       
       End Select
         
      Item.Categories = strCat
          Item.Save
        Err.Clear
       End If
       a = a + 1
       Debug.Print a
       If a = 3 Then a = 0
       

       
       
       
    If InStr(1, UCase(Item.Subject), UCase("Deposit")) Or InStr(1, UCase(Item.Body), UCase("Deposit")) <> 0 Then

      Select Case b
       Case 0
         strCat = "Case 5"
       Case 1
         strCat = "Case 6"
       
       End Select
         
      Item.Categories = strCat
          Item.Save
        Err.Clear
       End If
       b = b + 1
       Debug.Print b
       If b = 3 Then b = 0

    Reply
    • Diane Poremsky says

      March 29, 2021 at 9:35 pm

      it looks right... so  Debug.Print b always puts a 0 in the immediate window?

      Reply
  2. Mariah says

    July 27, 2020 at 11:13 am

    Could you post code to run this with a button on all emails in a shared inbox?

    I also keep getting an error at line:
    Set objDestFolder = Session.GetDefaultFolder(olFolderInbox).Folders(moveFolder)

    I tried using the other code for this line and it also fails. My folders are on the same level as the inbox.

    Reply
  3. Tyler says

    June 29, 2020 at 10:11 am

    Hi,
    This macro works perfectly. How would you modify the macro to skip a folder if you do not want to assign to them or if it is not there without manually changing the macro. I am looking to have a sub folder of "Do Not Assign" that management can move folders into and out of with the code still running and assigning emails to folders under the main inbox folder.

    Reply
  4. Tyler says

    June 10, 2020 at 4:53 pm

    Hi,
    This macro works perfectly. How would you modify the macro to skip a folder if you do not want to assign to them or if it is not there without manually changing the macro.

    Reply
  5. Cristina says

    April 30, 2019 at 2:45 pm

    Hi,
    I would like to combine 3 of the macros, first to categorize and then to forward the categorized e-mail and then move it to a specified folder. Could you please tell me how to do it?
    Thanks,
    Cristina

    Reply
    • Diane Poremsky says

      April 30, 2019 at 4:40 pm

      I'm assuming if category 1, then folder 1, and user 1.... you'd merge the select cases and the same with the actions -
      Select Case i
      Case 0
      strCat = "Case 0"
      movedFolder = "Folder1"
      sendTo = "Billy"
      Case 1
      ......

      End Select

      Item.categories = strCat
      Item.Save

      Set oForward = Item.Forward
      Set recip = oForward.recipients.Add(sendTo)
      recip.Resolve
      oForward.Display 'send

      Set objDestFolder = GetFolderPath(moveFolder)
      Item.Move objDestFolder

      End If

      Reply
  6. KauĂª says

    August 29, 2018 at 12:28 pm

    Hi Diane,

    I saw you answered my question in the other post. Thanks for try to help me.

    I'm sorry for my ignorance, I did not know until recently that there was programming in Outlook, I'm new to it.

    All I needed was that:
    When a new email arrives in the shared box, check if the sender is on the Global Contact List, if so, categorize as "Diamond Consultant", if not, classify as "Other Emails".

    Is there a practical way to do this?

    I tried accessing the generic email as JMaster and creating the rule but I could not figure out how to access the email key, it asks for a password and no one could tell me what it was, ie it will have to be by macro.

    The shared email is platform.comercial@diamond.com.br
    Rule to categorize as Consultant: The sender must be in the "Global Contact List".
    So categorize as a Consultant Diamond and the color of the category is dark blue.

    If it does not fit the rule does not do anything, or else, could classify as "Other Emails" and the category color is red.

    Please please please, help-me to do this. I'm from Brazil, and no Brazilian forum or website knew how to help me with this, I've been in this for two weeks.

    Thank you in advance.

    Reply
  7. ABI JACOB says

    June 5, 2018 at 8:10 am

    Hello Thanks for the Macro i used the same it works till the assiging the case post that its stuck at
    "Set objDesFolder = Application.Session.GetDefaultFolder(olFolderInbox).Parent.Folders(moveFolder)"

    the error i get is Object not found.

    I put the below code in This outlook session.

    Dim i As Long
    Private WithEvents olInboxItems As Items

    Private Sub Application_Startup()

    Dim objNS As NameSpace
    Set objNS = Application.Session
    Set olInboxItems = GetFolderPath("gl testing\Inbox").Items
    Set objNS = Nothing
    End Sub

    Private Sub olInboxItems_ItemAdd(ByVal Item As Object)
    Dim strCat As String

    If Item.Class = olMail Then

    Select Case i
    Case 0
    strCat = "Case 0"
    Case 1
    strCat = "Case 1"
    Case 2
    strCat = "Case 2"
    Case 3
    strCat = "Case 3"
    Case 4
    strCat = "Case 4"
    End Select

    Item.Categories = strCat
    Item.Save
    Err.Clear
    End If
    i = i + 1
    Debug.Print i
    If i = 5 Then i = 0

    Dim objDestFolder As Outlook.MAPIFolder
    Dim moveFolder As String

    If Item.Class = olMail Then

    Select Case i
    Case 0
    moveFolder = "AV"
    Case 1
    moveFolder = "AJ"
    Case 2
    moveFolder = "AK"
    Case 3
    moveFolder = "BB"
    Case 4
    moveFolder = "SS"
    End Select

    Set objDesFolder = Application.Session.GetDefaultFolder(olFolderInbox).Parent.Folders(moveFolder)
    Item.Move objDestFolder

    End If

    Set objDestFolder = Nothing
    End Sub

    and in module
    the GetFolderPath code.

    Can you please help?

    Thanks

    Reply
    • Diane Poremsky says

      June 7, 2018 at 12:31 am

      >> "Set objDesFolder = Application.Session.GetDefaultFolder(olFolderInbox).Parent.Folders(moveFolder)"
      >> the error i get is Object not found.

      each moveFolder is at the same level as the Inbox? That is where Outlook expects them. They also need to exist, outlook won't create them.

      Reply
      • ABI JACOB says

        June 8, 2018 at 12:46 am

        Hello Diane, Thanks for the response, The folder is under Inbox. and are already existing.

        Please see attached screenshot,

        Thanks
        Abi Jacob

  8. Joemar Coral says

    May 16, 2018 at 9:17 am

    Hi Diane,

    I'm creating a Macro to batch assign mail messages in the mailbox to different users. The code you mentioned is for Application start up. Can I use a command button to assign and categorise the mail messages to the users and transfer the outlook data to excel for monitoring?

    Reply
    • Diane Poremsky says

      June 7, 2018 at 12:38 am

      Yes, you can. The macor needs just a little tweaking. I have a stub macro that could do it with no changes to theat code, but it only runs on the selected message. If you want to run it on all messages in a folder, it needs a little more tweaking.

      At the simplest, you just need to change the item, dim the item, and set the item - this will run only on the selected item:
      Private Sub AssignMessages()
      Dim Item as Mailitem
      Dim objDestFolder As Outlook.MAPIFolder
      Dim moveFolder As String

      Set Item = Application.ActiveExplorer.Selection.Item(1)
      Dim objDestFolder As Outlook.MAPIFolder
      -- snip--

      Reply
  9. Irfan says

    January 31, 2018 at 3:45 pm

    Hi Diane
    This is almost exactly what i was looking for. Is there any way to adapt the code to assign the emails differently than round robin? For example if i have 4 people working the emails, for every 10 emails, i want the first 3 people to get 3 each and the 4th person to get 1. so if there are 20 emails waiting to be worked, persons 1-3 would get 3 each and person 4 would get 1 for the first 10 and then again persons 1-3 would get 3 each and person 4 would get 1

    thank you

    Reply
    • Diane Poremsky says

      January 31, 2018 at 11:48 pm

      Yeah, you could do that.
      This line does the count, change it to 10 10: If i = 5 Then i = 0
      The select case does the assigning. You need to account for 20, 0- 19, since it starts with 0. Do it like this to apply to more than one number:
      Select Case i
      Case 0, 1, 2
      ' do whatever
      Case 3,4,5
      ' do whatever

      Reply
    • Irfan says

      February 5, 2018 at 1:18 pm

      Hi Diane
      This worked amazingly. went with the option of assigning a category first and then coupled it with another macro to move the emails every 5 minutes.
      Thank you i really appreciate the quick response.

      Reply
  10. Candace says

    January 10, 2018 at 12:03 pm

    I'm using the round robin macro to assign emails equally to people in a department using a shared inbox where each person has an assigned category. However, I would like to be able to create an exception if an email is a reply to a specific person (but all people are replying with the same service email). I'm thinking that an exception could be added where if the body of the email has a specific person's name (from their signature), then the macro would sort that email into that person's category before continuing the round robin sorting. Is this possible?

    Reply
    • Diane Poremsky says

      January 10, 2018 at 4:23 pm

      That should work... at the very least, because you are leaving the mail in the folder, you can skip messages that begin Re:. They won't be categorized, but would group with the original message.

      If Item.Class = olMail Then
      if left(lcase(item.subject, 3)) <> "re:" then
      ' categorize
      end if
      end if

      Reply
      • Candace says

        January 10, 2018 at 4:34 pm

        Will this still work if the original message is uncategorized?

      • Diane Poremsky says

        January 10, 2018 at 4:35 pm

        Yes, because it is skipping all messages whose subject begins with re:

  11. Chris S. says

    February 7, 2017 at 10:00 am

    Hi Diane,

    I am trying to adapt the macro to assign a category by subject keyword instead of "round robin", but I am obviously missing something. In my case example, if the subject contains the world "pencil" I want it assigned to category "school"

    Private Sub olInboxItems_ItemAdd(ByVal Item As Object)
    Dim strCat As String

    If InStr(itm.Subject, "pencil") > 0 Then
    itm.UnRead = True
    itm.Categories = "school"
    itm.Save

    End If

    End Sub

    Any thoughts?

    Reply
    • Diane Poremsky says

      April 3, 2017 at 12:44 am

      try
      If Item.Class = olMail Then

      Select Case True
      Case InStr(1, LCase(Item.Subject), "reading")
      strCat = "school"
      Case InStr(1, LCase(Item.Subject), "keyword2")
      strCat = "Case 1"
      End Select

      Item.Categories = strCat
      Item.Save

      Reply
    • Diane Poremsky says

      April 3, 2017 at 1:01 am

      I updated the code to use - i have a mistake in it.

      Also, make sure you use the same object name as used in the rest of the macro: itm.Subject

      Reply
  12. Edd says

    October 18, 2016 at 10:52 pm

    I love the macro you shared. There is one more thing I need and I hope you can help out.

    Here is the situation:

    I have 15 members on my team that is divided into 4 member groups who handle different types of emails.

    What I am looking to get done is to assign emails based on the emails in their buckets. I do not want to overload anyone in that group with too many activities.

    Is there something in the script that I can add to make that work. also will this work on a generic mailbox. Thanks.

    Reply
    • Diane Poremsky says

      October 19, 2016 at 12:57 am

      The macro will work on any mailbox - you just need to tell it what folder to point to in this line:
      Set olInboxItems = GetFolderPath("Shared mailbox name\Inbox").Items

      I'm not sure i understand the 'bucket' problem - if one group is working on 20 messages and the other 3 only have 10 each, you want to skip the first group?

      Reply
  13. S@ndeep P@tel says

    July 4, 2016 at 1:07 pm

    Hi Diane,

    Such a great solution. But one more thing regarding this solution.

    It is possbile to do same thing with user's mailbox. In my organization Shred mailbox are added to user's outlook mailbox. Is it possible that any mail arrived in Shared Mailbox will move to another folder of Shared Mailbox from user's outlook vba? Because I don't know where the Shared mailbox is setup. we just use with user's mailbox.

    your help highly appreciated.

    Reply
    • Diane Poremsky says

      July 4, 2016 at 11:56 pm

      If the shared user sets up server side rules, they will run whether outlook is open and can move the mail (unless you are using conditions or actions that force the rules client side). If rules won't work, you can use the macro on any folder open in your mailbox. You may need to use the method here to identify the shared mailbox - https://www.slipstick.com/developer/working-vba-nondefault-outlook-folders/#shared

      Reply
  14. Ritesh Patil says

    June 8, 2016 at 3:36 am

    Hello,
    I am trying to run the above steps but i am getting the below error every time i run the macro
    "Object Variable or with block variable not set"
    Can you please please help me.
    My Code:

    Under : thisOutlookSession

    Dim i As Long
    Public WithEvents olInboxItems As Items

    Public Sub Application_Startup()
    Dim objNS As NameSpace
    Set objNS = Application.Session
    Set olInboxItems = GetFolderPath("Fulfilment.qatar\Inbox\Team Helpdesk May 2016").Items
    Set objNS = Nothing
    End Sub

    Public Sub olInboxItems_ItemAdd(ByVal Item As Object)
    Dim strCat As String

    If Item.Class = olMail Then

    Select Case i
    Case 0
    strCat = "Case 0"
    Case 1
    strCat = "Case 1"
    Case 2
    strCat = "Case 2"
    Case 3
    strCat = "Case 3"
    Case 4
    strCat = "Case 4"
    End Select

    Item.Categories = strCat
    Item.Save
    Err.Clear
    End If
    i = i + 1
    Debug.Print i
    If i = 5 Then i = 0
    End Sub

    Under :Module 1

    ' Use the GetFolderPath function to find a folder in non-default mailboxes
    Function GetFolderPath(ByVal FolderPath As String) As Outlook.Folder
    Dim oFolder As Outlook.Folder
    Dim FoldersArray As Variant
    Dim i As Integer

    On Error GoTo GetFolderPath_Error
    If Left(FolderPath, 2) = "\\" Then
    FolderPath = Right(FolderPath, Len(FolderPath) - 2)
    End If
    'Convert folderpath to array
    FoldersArray = Split(FolderPath, "\")
    Set oFolder = Application.Session.Folders.Item(FoldersArray(0))
    If Not oFolder Is Nothing Then
    For i = 1 To UBound(FoldersArray, 1)
    Dim SubFolders As Outlook.Folders
    Set SubFolders = oFolder.Folders
    Set oFolder = SubFolders.Item(FoldersArray(i))
    If oFolder Is Nothing Then
    Set GetFolderPath = Nothing
    End If
    Next
    End If
    'Return the oFolder
    Set GetFolderPath = oFolder
    Exit Function

    GetFolderPath_Error:
    Set GetFolderPath = Nothing
    Exit Function
    End Function

    Thanks,
    Ritesh

    Reply
    • Diane Poremsky says

      July 5, 2016 at 12:06 am

      Is this spelled correctly and in the proper case?
      Fulfilment.qatar\Inbox\Team Helpdesk May 2016

      Reply
  15. SturiGellar says

    March 29, 2016 at 9:26 am

    Hi Diane,

    Great post, wasted on me as I'm obviously missing something with the round robin macro.

    I'm testing this on Outlook 2007 Pro with an Exchange mailbox as primary/default inbox so haven't added the GetFolderPath section.

    I've added the Step 1 and placed both ItemAdd sections which assign a category round robin and move messages to a folder beneath it. However when I try and compile it, it has an issue with the 'Private WithEvents olInboxItems As Items' statement

    The error I get is - Compile Error, Only valid in object module

    Hope you can help

    Thanks
    Stuart

    Reply
  16. azgi says

    November 2, 2015 at 3:05 am

    Hi Diane,
    Thank you so much for sharing this macro. It is my first trying in macro, hence I just try to understand you instruction and I still must learn about each meaning of macro code. I have a question, but let me explain my first trying:
    1. I double click ThisOutlookSession and I put macro code as follow
    Dim i As Long Private WithEvents olInboxItems As Items
    Private Sub Application_Startup()
    ……..
    Until
    ……..
    Nothing End Sub
    2. Then I add this one of ItemAdd Macro as follow after Nothing End Sub
    Private Sub olInboxItems_ItemAdd(ByVal Item As Object)
    Dim strCat As String
    ……
    Until
    …..
    Debug.Print i
    If i = 5 Then i = 0
    End Sub
    3. Then I created module and I put this macro
    ' Use the GetFolderPath function to find a folder in non-default mailboxes Function GetFolderPath
    …..
    Until
    ….
    Set GetFolderPath = Nothing Exit Function End Function
    My question is:
    1. Am I correct? But why my macro cannot be run?
    2. My shared folder is xxx.support@xxx.com therefore for getFolderPath is it correct if I only state
    GetFolderPath("Inbox")? Or is it supposed to be GetFolderPath("xxx.support@xxx.com \Inbox")

    Reply
    • Diane Poremsky says

      January 6, 2016 at 12:39 am

      you need to use the full display name as seen in the folder list and the folder name, so GetFolderPath("xxx.support@xxx.com \Inbox") would be correct.

      Is macro security set to low? Is the macro not running or not doing anything?

      Reply
  17. sorrybaws says

    September 3, 2015 at 2:17 am

    Hi there - I hope I'm not repeating this question but I couldn't find it elsewhere: I need to transfer mail from a shared mailbox to a .pst. How do I tell the VBA script which inbox to take mail from?

    Reply
    • Diane Poremsky says

      September 3, 2015 at 7:51 am

      This is the part that tells the macro on this page where to look:
      Private Sub Application_Startup()
      Dim objNS As NameSpace
      Set objNS = Application.Session
      Set olInboxItems = GetFolderPath("Shared mailbox name\Inbox").Items
      Set objNS = Nothing
      End Sub

      so, you replace the piece of code that points to the folder in your code with
      GetFolderPath("Shared mailbox name\Inbox")
      and get the getfolderpath function from https://www.slipstick.com/developer/code-samples/use-macro-assign-messages-shared-mailbox/#getfolderpath - add it to a new module or after your macro.

      Reply
  18. Nravota says

    August 24, 2015 at 9:19 am

    Ok, now it assigns categories to all the mails with attachments but If the messages are more than 14-15, it skips some categories in the middle, so it is not always Case 0, Case 1 and Case 2 as I want it to be. How can I fix this? It is important that the different categories appear even number of times and if the mails are more than that simply not to put category, as in your example. Here is what I came up with:

    For Each obj In objItems

    intcount = obj.Attachments.Count

    If intcount > 0 Then

    For Each oAtt In obj.Attachments
    Debug.Print oAtt.Size
    On Error Resume Next
    If oAtt.Size 30000 Then

    With obj

    Select Case i
    Case 0
    strCat = "Nasko"
    Case 1
    strCat = "Kremi"
    Case 2
    strCat = "Gabi"
    End Select
    obj.Categories = strCat
    obj.Save
    Err.Clear

    i = i + 1
    Debug.Print i
    If i = 3 Then i = 0

    End With

    End If

    NextAtt:

    Next

    End If

    Next

    Reply
  19. Felix Lu says

    August 18, 2015 at 10:04 am

    Is it possible to assign categories based on rules that you store "offshore". E.g. The macro refers to an excel spreadsheet where you stored the rules (The excel cells A1 & B1 stores the words Bread and Food respectively.) If an incoming mail's subject header has the word bread, the macro refers to the excel sheet and categorizes the email as Food etc.

    Reply
    • Diane Poremsky says

      August 18, 2015 at 11:34 am

      you can, but it would be best to read the sheet at startup and store the values in an array - reading the sheet each time the macro runs could slow things down and increase the chances that some messages are missed.

      Reply
  20. Nravota says

    August 10, 2015 at 5:57 am

    Hi Diane, I am using the code to assign categories only on the mails with attachment and I added the if statement, but the code still puts categories to all the mails.. Can you pls help? Here is the code:

    Option Explicit
    Public Sub Assign_Categories()

    Dim Ns As Outlook.NameSpace
    Dim objOL As Outlook.Application

    Dim i As Integer
    Dim objOutlookItem As Object
    Dim objItems As Outlook.Items
    Dim objFolder As Outlook.MAPIFolder
    Dim obj As Object
    Dim strCat As String

    Set Ns = Application.GetNamespace("MAPI")
    Set objOL = Outlook.Application
    Set objFolder = objOL.ActiveExplorer.CurrentFolder
    Set objItems = objFolder.Items

    For Each obj In objItems

    With obj

    If obj.Attachments.Count > 0 Then

    Select Case i
    Case 0
    strCat = "John"
    Case 1
    strCat = "Robin"
    Case 2
    strCat = "Gregory"
    End Select
    obj.Categories = strCat
    obj.Save
    Err.Clear

    i = i + 1
    Debug.Print i
    If i = 3 Then i = 0

    End If

    End With

    Next
    Set obj = Nothing
    Set objOutlookItem = Nothing
    Set objItems = Nothing
    Set objFolder = Nothing
    Set objOL = Nothing
    End Sub

    Maybe sth with the icounter is not correct here? Thanks a lot in advance!

    Reply
    • Diane Poremsky says

      August 18, 2015 at 1:19 pm

      it looks to me like its because the attachment check is inside the With. Try it outside of the With, if nothing else, it'll jump to the next message a split second faster.

      Reply
  21. Nravota says

    August 4, 2015 at 8:50 am

    Hi Diane,

    Thank you for this link, I successfully adapted it. I just wanted to ask you if there is a way to assign the categories only for the mails with attachment?

    Reply
    • Diane Poremsky says

      August 6, 2015 at 12:38 am

      You can use an if statement - it should work after the move, if not, put it before the message is moved.
      If Item.Attachments.Count > 0 Then
      item.categories = "category name"
      end if

      Reply
  22. Nravota says

    August 3, 2015 at 9:08 am

    Is there also a way to assign the rotating categories within a sub, so the user can decide when exactly the mails in the inbox should be categorized?

    Reply
    • Diane Poremsky says

      August 4, 2015 at 12:29 am

      To run the macro manually? Sure - with a little tweaking, it can be used manually. I have a sample macro that works on all messages in a folder here: https://www.slipstick.com/developer/code-samples/working-items-folder-selected-items/ add the category code to it to apply categories to messages in a folder.

      Reply
      • Paul H says

        January 26, 2017 at 2:48 pm

        Hi Diane,

        I'm basically brand new to VB and I'm trying to get the macro to run manually on selected mail objects in a shared mailbox. Can you expand on this a bit more?

        I've tried copying the category code (starting with the "Dim strCat As String" line, ending with "If i = 5 Then i = 0 line") and pasting it over the Debug.Print .Subject line in the "Work with Selected items in any folder" code but I keep getting a variable not defined error where it highlights the i in Select Case i. What am I doing wrong?

  23. Nravota says

    July 22, 2015 at 3:55 am

    Hi, this macro is great, but I have one question - will it assign color categories only in the Inbox folder of the non-default mailbox or it will also go in all folders in the non-default mailbox. For instance, I have inbox folder but I also have archives folder with many subfolders in the same mailbox. I do not want to change what is already there. I only want the macro to put rotating categories in the inbox folder.

    Reply
    • Diane Poremsky says

      July 29, 2015 at 7:55 am

      It assigns categories to new messages as they arrive in the folder identified here:
      GetFolderPath("Shared mailbox name\Inbox"). It won't touch other folders.

      Reply
      • Abbas says

        February 18, 2018 at 9:30 am

        I did the same as mentioned above.It through an error as object variable or with block variable not set

      • Diane Poremsky says

        February 20, 2018 at 11:57 pm

        That means you are using a variable name that is not set. What line does it stop on? Did you edit the code?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Visit Slipstick Forums.
What's New at Slipstick.com

Latest EMO: Vol. 31 Issue 8

Subscribe to Exchange Messaging Outlook






Support Services

Do you need help setting up Outlook, moving your email to a new computer, migrating or configuring Office 365, or just need some one-on-one assistance?

Our Sponsors

CompanionLink
ReliefJet
  • Popular
  • Latest
  • Week Month All
  • Deleting Auto-Complete Entries No Longer Works
  • Use Classic Outlook, not New Outlook
  • How to Remove the Primary Account from Outlook
  • How to Hide or Delete Outlook's Default Folders
  • Removing Suggested Accounts in New Outlook
  • Disable "Always ask before opening" Dialog
  • Adjusting Outlook's Zoom Setting in Email
  • Reset the New Outlook Profile
  • Change Outlook's Programmatic Access Options
  • Use Public Folders In new Outlook
  • Deleting Auto-Complete Entries No Longer Works
  • Sync Issues and Errors with Gmail and Yahoo accounts
  • Error Opening iCloud Appointments in Classic Outlook
  • Opt out of Microsoft 365 Companion Apps
  • Mail Templates in Outlook for Windows (and Web)
  • Urban legend: Microsoft Deletes Old Outlook.com Messages
  • Buttons in the New Message Notifications
  • Move Deleted Items to Another Folder Automatically
  • Open Outlook Templates using PowerShell
  • Count and List Folders in Classic Outlook
Ajax spinner

Recent Bugs List

Microsoft keeps a running list of issues affecting recently released updates at Fixes or workarounds for recent issues in classic Outlook (Windows).

For new Outlook for Windows: Fixes or workarounds for recent issues in new Outlook for Windows .

Outlook for Mac Recent issues: Fixes or workarounds for recent issues in Outlook for Mac

Outlook.com Recent issues: Fixes or workarounds for recent issues on Outlook.com

Office Update History

Update history for supported Office versions is at Update history for Office

Outlook Suggestions and Feedback

Outlook Feedback covers Outlook as an email client, including Outlook Android, iOS, Mac, and Windows clients, as well as the browser extension (PWA) and Outlook on the web.

Outlook (new) Feedback. Use this for feedback and suggestions for Outlook (new).

Use Outlook.com Feedback for suggestions or feedback about Outlook.com accounts.

Other Microsoft 365 applications and services




New Outlook Articles

Deleting Auto-Complete Entries No Longer Works

Sync Issues and Errors with Gmail and Yahoo accounts

Error Opening iCloud Appointments in Classic Outlook

Opt out of Microsoft 365 Companion Apps

Mail Templates in Outlook for Windows (and Web)

Urban legend: Microsoft Deletes Old Outlook.com Messages

Buttons in the New Message Notifications

Move Deleted Items to Another Folder Automatically

Open Outlook Templates using PowerShell

Count and List Folders in Classic Outlook

Newest Code Samples

Open Outlook Templates using PowerShell

Count and List Folders in Classic Outlook

Insert Word Document into Email using VBA

Warn Before Deleting a Contact

Use PowerShell to Delete Attachments

Remove RE:, FWD:, and Other Prefixes from Subject Line

Change the Mailing Address Using PowerShell

Categorize @Mentioned Messages

Send an Email When You Open Outlook

Delete Old Calendar Events using VBA

VBA Basics

How to use the VBA Editor

Work with open item or selected item

Working with All Items in a Folder or Selected Items

VBA and non-default Outlook Folders

Backup and save your Outlook VBA macros

Get text using Left, Right, Mid, Len, InStr

Using Arrays in Outlook macros

Use RegEx to extract message text

Paste clipboard contents

Windows Folder Picker

Custom Forms

Designing Microsoft Outlook Forms

Set a custom form as default

Developer Resources

Developer Resources

Developer Tools

VBOffice.net samples

SlovakTech.com

Outlook MVP David Lee

Repair PST

Convert an OST to PST

Repair damaged PST file

Repair large PST File

Remove password from PST

Merge Two Data Files

Sync & Share Outlook Data

  • Share Calendar & Contacts
  • Synchronize two computers
  • Sync Calendar and Contacts Using Outlook.com
  • Sync Outlook & Android Devices
  • Sync Google Calendar with Outlook
  • Access Folders in Other Users Mailboxes

Diane Poremsky [Outlook MVP]

Make a donation

Mail Tools

Sending and Retrieval Tools

Mass Mail Tools

Compose Tools

Duplicate Remover Tools

Mail Tools for Outlook

Online Services

Calendar Tools

Schedule Management

Calendar Printing Tools

Calendar Reminder Tools

Calendar Dates & Data

Time and Billing Tools

Meeting Productivity Tools

Duplicate Remover Tools

Productivity

Productivity Tools

Automatic Message Processing Tools

Special Function Automatic Processing Tools

Housekeeping and Message Management

Task Tools

Project and Business Management Tools

Choosing the Folder to Save a Sent Message In

Run Rules on messages after reading

Help & Suggestions

Submit Outlook Feature Requests

Slipstick Support Services

Buy Microsoft 365 Office Software and Services

Visit Slipstick Forums.

What's New at Slipstick.com

Home | Outlook User | Exchange Administrator | Office 365 | Outlook.com | Outlook Developer
Outlook for Mac | Common Problems | Utilities & Addins | Tutorials
Outlook & iCloud Issues | Outlook Apps
EMO Archives | About Slipstick | Slipstick Forums
Submit New or Updated Outlook and Exchange Server Utilities

Send comments using our Feedback page
Copyright © 2026 Slipstick Systems. All rights reserved.
Slipstick Systems is not affiliated with Microsoft Corporation.