Outlook programming : Looping individual mails inside the Inbox


   1:  'myLoop method
   2:  Sub myLoop()
   3:   
   4:     'Declaration
   5:      Dim olApp As Outlook.Application
   6:      Dim olNs As Outlook.NameSpace
   7:      Dim olFldr As Outlook.MAPIFolder
   8:      Dim olItms As Outlook.Items
   9:      Dim olMail As Object
  10:   
  11:      Set olApp = New Outlook.Application
  12:      Set olNs = olApp.GetNamespace("MAPI")
  13:      Set olFldr = olNs.GetDefaultFolder(olFolderInbox)
  14:      Set olItms = olFldr.Items
  15:   
  16:      'Loop the items     
  17:      For Each olMail In olItms
  18:          'Here you need to use olMail Object to inspect individual mails inside the Inbox
  19:      Next olMail
  20:   
  21:      'Release the objects appropriately
  22:      Set olFldr = Nothing
  23:      Set olNs = Nothing
  24:      Set olApp = Nothing
  25:  End Sub
Comments (3)
  1. JP says:

    Deva,

    If this code is being used natively in Outlook, why would you need to create a new Application object?

    Set olApp = New Outlook.Application

    Also, if there are other items in the Inbox besides MailItems, the code might fail. I would add a test inside the For Each Loop to make sure it’s an email (not an appointment, task, etc) before proceeding.

  2. JP says:

    Deva,

    If this code is being used natively in Outlook, why would you need to create a new Application object?

    Set olApp = New Outlook.Application

    Also, if there are other items in the Inbox besides MailItems, the code might fail. I would add a test inside the For Each Loop to make sure it’s an email (not an appointment, task, etc) before proceeding.

  3. Deva [MSFT] says:

    Hi JP,

    Thanks for your update. Sorry to providing the comments late!!

    1) First this is not a VBA code snippet, it’s VB.Net snippet (please refer tag ".Net"). If you use in VBA, certainly the NEW keyword shouldn’t be used.

    2) Second, this is a basic code snippet as i mentioned earlier (please refer disclaimer), which won’t suit for direct production ready usage.

    Hope this helps.

Comments are closed.

Skip to main content