• Outlook User
  • Exchange Admin
  • Office 365
  • Outlook Developer
  • Outlook.com
  • Outlook Mac
  • Common Problems
    • Outlook BCM
    • Utilities & Addins
    • Video Tutorials
    • EMO Archives
    • Outlook Updates
    • Outlook Apps
    • Outlook & iCloud Issues
    • Forums

Working with All Items in a Folder or Selected Items

Slipstick Systems

› Developer › Code Samples › Working with All Items in a Folder or Selected Items

Last reviewed on August 31, 2016   —  No Comments

August 7, 2014 by Diane Poremsky Leave a Comment

These two samples contains the basic code for working with all items in a selected folder or selected items in a folder. The code sample prints the item subject in the Immediate window (Ctrl+6).

Because the code uses generic objects instead of specific objects, it will work with all item types.

Work with all items in any folder

Option Explicit
Public Sub DoSomethingFolder()
    Dim objOL As Outlook.Application
    Dim objItems As Outlook.Items
    Dim objFolder As Outlook.MAPIFolder
    Dim obj As Object
 
    Set objOL = Outlook.Application
    Set objFolder = objOL.ActiveExplorer.CurrentFolder
    Set objItems = objFolder.Items
 
    For Each obj In objItems
 
     With obj
 
    ' do whatever
       Debug.Print .Subject
     
     End With

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

To work with all items in a specific folder, replace
Set objFolder = objOL.ActiveExplorer.CurrentFolder
with GetDefaultFolder and locate the folder (if it's not a default folder).
Set objFolder = Ns.GetDefaultFolder(olFolderCalendar)
Set objFolder = Ns.GetDefaultFolder(olFolderCalendar).Folders("Subfolder")

You'll also need to add these two lines to the macro - Dim Ns should be the first Dim statement, and Set Ns needs to be the first Set statement.

Dim Ns As Outlook.NameSpace
Set Ns = Application.GetNamespace("MAPI")

See VBA and non-default Outlook Folders for more information.

Work with Selected items in any folder

Option Explicit

Public Sub DoSomethingSelection()
    Dim Session As Outlook.NameSpace
    Dim currentExplorer As Explorer
    Dim Selection As Selection
    
    Dim obj As Object

    Set currentExplorer = Application.ActiveExplorer
    Set Selection = currentExplorer.Selection

    For Each obj In Selection
 
     With obj
 
    ' do whatever
       Debug.Print .Subject
     
     End With

    Next

    Set Session = Nothing
    Set currentExplorer = Nothing
    Set obj = Nothing
    Set Selection = Nothing

End Sub

Discuss in our community
Working with All Items in a Folder or Selected Items was last modified: August 31st, 2016 by Diane Poremsky
  • Click to share on Twitter (Opens in new window)
  • Click to share on Facebook (Opens in new window)
  • Click to share on Google+ (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Share on Skype (Opens in new window)
  • Click to share on Pocket (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to print (Opens in new window)

Related Posts:

  • Use VBA to get an Appointment's Time Zone
  • Save Messages as *.DOC File Type
  • Open All Hyperlinks in an Outlook Email Message
  • Set a reminder on selected items in the To-Do List

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.

Leave a Reply

Be the First to Comment!

2500
Photo and Image Files
 
 
 
Audio and Video Files
 
 
 
Other File Types
 
 
 
2500
Photo and Image Files
 
 
 
Audio and Video Files
 
 
 
Other File Types
 
 
 
  Subscribe  
Notify of
Alan
Alan
Share On TwitterShare On Google

Hi Diane,
Do you have any suggestions around how to handle the scenario where you want to loop through each object in a selection if one or more items are selected but otherwise loop through each object in the folder if no items are selected? Is there any way to do something along the lines of this pseudocode:

Public Sub DoSomething()
'Dim stuff
'Set stuff
If Selection.Count > 0 Then
objItems = Selection
Else
objItems = objFolder.Items
End If
For Each obj in objItems
'do whatever
Next
End Sub

Thanks!

Vote Up00Vote Down Reply
July 25, 2017 7:34 pm
Diane Poremsky
Diane Poremsky
Share On TwitterShare On Google

That would be difficult, i'd think... because you'll always have at least 1 selected. You can loop the folder if 1 is selected, or do the selection if more than one is selected.
This little tweak will do the entire folder if 1 is selected, or only the selection if more than one is selected.

Set Selection = currentExplorer.Selection
If Selection.Count = 1 Then
' run the other macro
DoSomethingFolder

Else

    For Each obj In Selection
'--snip--
    Next
End If
Vote Up00Vote Down Reply
July 25, 2017 11:34 pm
Sam
Sam
Share On TwitterShare On Google

Hi Diane,
I have an issue, I am hoping perhaps you or someone here can provide insight.
For a selected email, I assign user defined category from combobox and move the email to a folder. It works fine with emails in my Inbox.

When I do the same for emails in shared inbox, it simply moves it without assigning category. And there is no error message.

Any help appreciated.

Thank you

Vote Up00Vote Down Reply
January 4, 2017 5:53 am
Diane Poremsky
Diane Poremsky
Share On TwitterShare On Google

Does the category exist in the shared mailbox? Are you using code with the custom form? If so, it could be something with the code too.

Vote Up00Vote Down Reply
February 6, 2017 12:28 am
Eric Li
Eric Li
Share On TwitterShare On Google

Hi Diane,

Thank you for this tutorial, we use it to send all drafts in draft folder using a specific email address (SentOnBehalfOfName).

However, the macro will only send half of the drafts in the folder, do you know if there's a fix for this?

thank you very much.

Public Sub DoSomethingFolder()
Dim objOL As Outlook.Application
Dim objItems As Outlook.Items
Dim objFolder As Outlook.MAPIFolder
Dim obj As Object

Set objOL = Outlook.Application
Set objFolder = objOL.ActiveExplorer.CurrentFolder
Set objItems = objFolder.Items

For Each obj In objItems

With obj

.SentOnBehalfOfName = "XXX@gmail.com"
.Send

End With

Next

Set obj = Nothing
Set objItems = Nothing
Set objFolder = Nothing
Set objOL = Nothing

End Sub

Vote Up00Vote Down Reply
September 29, 2016 6:50 pm
Diane Poremsky
Diane Poremsky
Share On TwitterShare On Google

Sorry I missed this earlier. I wonder if it is losing the count as messages are sent, much like deleting items will get every other one because the index # changes as you delete. The fix is to count backwards - For i = 1 to objitems.count step -1

Vote Up00Vote Down Reply
February 6, 2017 12:35 am
HermanT
HermanT
Share On TwitterShare On Google

I changed it for a specific folder.
Then i get a error:
Fout -2147221233 (8004010f) tijdens uitvoering
De bewerking is mislukt. Kan een object niet vinden
Why? And how to solve it?

Vote Up00Vote Down Reply
September 16, 2016 9:19 am
Diane Poremsky
Diane Poremsky
Share On TwitterShare On Google

what code are you using to identify the folder? The error says 'Can not find an object' - and I'm guessing the object it can't find is the folder.

Vote Up00Vote Down Reply
September 18, 2016 12:55 am
Ashish T
Ashish T
Share On TwitterShare On Google

i have already made code to save attachment from share mail box to sharepoint. but i am getting difficulties in saving attachment from specific date range kindly help

Vote Up00Vote Down Reply
August 29, 2016 5:45 am
Diane Poremsky
Diane Poremsky
Share On TwitterShare On Google

so you want to save only those in a specific range, not the file date?

Two methods: Select them then run a macro (second macro) or set the macro to check the date on each message in the folder.

if you are calculating the date using today's date as the base, you can do something like this:
intDateDiff = DateDiff("d", obj.SentOn, Now)
If intDateDiff > 7 Then ' older than 7 days
' do whatever
end if

Vote Up00Vote Down Reply
August 29, 2016 10:45 am
ClintonA
Share On TwitterShare On Google

Dianne,
Great code. Do you know how to adapt this to modify the calendar folder to delete the subject and add the organizer? We have it set correctly moving forward but after migration all previous reservations show the subject instead of the organizer.
Any help appreciated.
Thank you,
Have a great one

Vote Up00Vote Down Reply
July 14, 2016 2:00 pm
Diane Poremsky
Diane Poremsky
Share On TwitterShare On Google

I assume you mean different code than is what on this page... you'll use code similar to .subject = .organizer

if you are using exchange, the new server can be configured to show the organizers name on resource calendars.

Vote Up00Vote Down Reply
July 19, 2016 7:35 am
Alex Chaplin
Alex Chaplin
Share On TwitterShare On Google

Dianne thanks a lot for your code on "Work with all items in any folder". I was able to adapt it to create a list of sender names from 148 email responses saved in an Outlook folder saving me a lot of tedium and fat fingering to create a dg group. I also wanted to look at emails attached to some of the emails in the folder and get those sender names as well. I looked at different objects and attributes but couldn't find it. Is there a way to do this? Thanks in advance.

Vote Up00Vote Down Reply
July 1, 2016 3:56 pm
Diane Poremsky
Diane Poremsky
Share On TwitterShare On Google

The emails were attachments on other emails?

Vote Up00Vote Down Reply
July 2, 2016 12:54 am
Alex Chaplin
Alex Chaplin
Share On TwitterShare On Google
Diane, I kept hitting an "Outlook cannot do this action on this type of attachment" error. This site http://www.outlookcode.com/threads.aspx?forumid=2&messageid=5551 provided the solution. The problem was embedded olOLE attachments which couldn't be accessed like other attachments. The code ran fine with the fix applied to check for objAttachments.Item(i).Type 6. See below. Thanks a lot for your help. Much appreciated. This code is in the WITH loop Set objAttachments = obj.Attachments lngCount = objAttachments.Count If lngCount > 0 Then For i = lngCount To 1 Step -1 ' Added code fix here If objAttachments.Item(i).Type 6 Then strFile = objAttachments.Item(i).FileName If Right(strFile, 4) = ".msg" Then strFile = strFolderpath & i & strFile objAttachments.Item(i).SaveAsFile strFile ' Debug.Print strFile Set objItem = Application.CreateItemFromTemplate(strFile) 'Application.ActiveInspector.CurrentItem ' Debug.Print "attachment", objItem.SenderName, objItem.SenderEmailAddress Debug.Print objItem.SenderName; ";" objItem.Close olDiscard End If End If Next End If
Vote Up00Vote Down Reply
July 12, 2016 2:16 pm
Diane Poremsky
Diane Poremsky
Share On TwitterShare On Google

you need to check for attachments, save & open them. open attached messages

Vote Up00Vote Down Reply
July 2, 2016 1:49 am
Dimas
Dimas
Share On TwitterShare On Google

Hi Diane!
I'm trying to get the size of each folder in the Inbox. That's not hard to do, just takes a lil time.
But, I don't know (and haven't been able to find) how to pull information from non-cached emails. I mean, those that only show after you click "Click here to view more on Microsoft Exchange".
Do you know how to do this, will you help me?

Thanks a lot!

Dimas

Vote Up0-1Vote Down Reply
May 30, 2016 12:11 pm
Diane Poremsky
Diane Poremsky
Share On TwitterShare On Google

What version of Exchange? Do you need to use VBA or can you use powershell?

Vote Up1-1Vote Down Reply
July 12, 2016 4:01 pm

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

Latest EMO: Vol. 23 Issue 10

Subscribe to Exchange Messaging Outlook






Our Sponsors

  • Popular
  • Latest
  • Week Month All
  • This operation has been cancelled due to restrictions This operation has been cancelled due to restrictions
  • Adjusting Outlook's Zoom Setting in Email Adjusting Outlook's Zoom Setting in Email
  • How to Remove the Primary Account from Outlook How to Remove the Primary Account from Outlook
  • Pictures Don't Display in Outlook Messages Pictures Don't Display in Outlook Messages
  • Outlook is Not Recognized as the Default Email Client Outlook is Not Recognized as the Default Email Client
  • To Cc or Bcc a Meeting Request To Cc or Bcc a Meeting Request
  • Remove a password from an Outlook *.pst File Remove a password from an Outlook *.pst File
  • The Signature or Stationery and Fonts button doesn't work The Signature or Stationery and Fonts button doesn't work
  • Understanding Outlook's Auto-Complete Cache (*.NK2) Understanding Outlook's Auto-Complete Cache (*.NK2)
  • Exchange Account Set-up Missing in Outlook 2016 Exchange Account Set-up Missing in Outlook 2016
  • iCloud error: Outlook isn't configured to have a default profile iCloud error: Outlook isn't configured to have a default profile
  • Setting Custom Reminder Times Setting Custom Reminder Times
  • Add Additional Addresses to Room Mailboxes Add Additional Addresses to Room Mailboxes
  • Create a Task from a Message and include the Attachment Create a Task from a Message and include the Attachment
  • Forward email messages by date Forward email messages by date
  • Open multiple Outlook windows when Outlook starts Open multiple Outlook windows when Outlook starts
  • Office 365 Fraud Detection Checks Office 365 Fraud Detection Checks
  • Outlook Request: Calendar Details View Outlook Request: Calendar Details View
  • Outlook's "Not Junk" option isn't available Outlook's "Not Junk" option isn't available
  • Outlook Tip: Show all Mondays in the Calendar Outlook Tip: Show all Mondays in the Calendar
Ajax spinner

Newest VBA Samples

Open multiple Outlook windows when Outlook starts

Set most frequently used Appointment Time Zones

How to change the From field on incoming messages

VBA: File messages by client code

Update Contact Area Codes

Set a reminder on selected items in the To-Do List

Replicate GTD: Create a task after sending a message

Use VBA to read fields in attached messages

Move Outlook Folders using VBA

Replicate Smart Lookup using a macro

Recent Bugs List

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

Windows 10 Issues

  • iCloud, Outlook 2016, and Windows 10
  • Better Outlook Reminders?
  • Coming Soon to Windows 10: Office 365 Search
  • Outlook Links Won’t Open In Windows 10
  • BCM Errors after Upgrading to Windows 10
  • Outlook can’t send mail in Windows 10: error Ox800CCC13
  • Missing Outlook data files after upgrading Windows?

Outlook 2016 Top Issues

  • The Windows Store Outlook App
  • Emails are not shown in the People Pane (Fixed)
  • Calendars aren’t printing in color
  • The Signature or Stationery and Fonts button doesn’t work
  • Outlook’s New Account Setup Wizard
  • BCM Errors after October 2017 Outlook Update
  • Excel Files Won’t Display in Reading Pane
  • Outlook 2016: No BCM
  • Exchange Account Set-up Missing in Outlook 2016

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

Outlook-tips.net Samples

VBOffice.net samples

OutlookCode.com

SlovakTech.com

Outlook MVP David Lee

MSDN Outlook Dev Forum

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
  • “Live” Group Calendar Tools

Convert to / from Outlook

  • Converting Messages and Calendar or
    Address books
  • Moving Outlook to a New Computer
  • Moving Outlook 2010 to a new Windows computer
  • Moving from Outlook Express to Outlook

Recover Deleted Items

  • Recover deleted messages from .pst files
  • Are Deleted Items gone forever in Outlook?

Outlook 2013 Absolute Beginner's Guide

Diane Poremsky [Outlook MVP]

Make a donation

Calendar Tools

Schedule Management

Calendar Printing Tools

Calendar Reminder Tools

Calendar Dates & Data

Time and Billing Tools

Meeting Productivity Tools

Duplicate Remover Tools

Mail Tools

Sending and Retrieval Tools

Mass Mail Tools

Compose Tools

Duplicate Remover Tools

Mail Tools for Outlook

Online Services

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

Outlook Suggestion Box (UserVoice)

Slipstick Support Services

Contact Tools

Data Entry and Updating

Duplicate Checkers

Phone Number Updates

Contact Management Tools

Sync & Share

Share Calendar & Contacts

Synchronize two machines

Sharing Calendar and Contacts over the Internet

More Tools and Utilities for Sharing Outlook Data

Access Folders in Other Users Mailboxes

View Shared Subfolders in an Exchange Mailbox

"Live" Group Calendar Tools

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

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

You are going to send email to

Move Comment