Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference a folder not under the default inbox

Tags:

vba

outlook

I've tried countless ways of deleting items from a custom folder called "Spam Digests" older than 14 days. I have successfully done this when I nest this folder underneath the olDefaultFolder(Inbox) but when I have it outside of the default inbox, I cannot reference it as I receive object not found.

Here is what I have and I cannot seem to figure out why the object is not found when referencing "fldSpamDigest"

    Dim outapp As Outlook.Application
    Set outapp = CreateObject("outlook.application")
    Dim olitem As Object
    Dim fldSpamDigest As Outlook.MAPIFolder

    Set fldSpamDigest = outapp.GetNamespace("MAPI").Folders("Spam Digests")
    For Each olitem In fldSpamDigest.Items
        If DateDiff("d", olitem.CreationTime, Now) > 14 Then olitem.Delete
    Next

    Set fldSpamDigest = Nothing
    Set olitem = Nothing
    Set outapp = Nothing
like image 352
user3487671 Avatar asked Jan 25 '18 15:01

user3487671


2 Answers

GetDefaultFolder(olFolderInbox) is a shortcut.

You can reference any folder the long way.

Sub reference_walk_the_path()

    Dim outapp As Outlook.Application
    Set outapp = CreateObject("outlook.application")

    Dim olitem As Object
    Dim fldSpamDigest As Outlook.MAPIFolder

    ' from the default inbox to the parent which is your mailbox
    Set fldSpamDigest = outapp.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox).Parent
    ' from the mailbox to a folder at the same level as the Inbox 
    Set fldSpamDigest = fldSpamDigest.folders("Spam Digests")

    ' or
    ' directly from the mailbox to a folder at the same level as the Inbox 
    'Set fldSpamDigest = outapp.GetNamespace("MAPI").folders("your email address").folders("Spam Digests")

    For Each olitem In fldSpamDigest.Items
        If dateDiff("d", olitem.CreationTime, Now) > 14 Then olitem.Delete                
    Next

    Set fldSpamDigest = Nothing
    Set olitem = Nothing
    Set outapp = Nothing

End Sub
like image 112
niton Avatar answered Nov 02 '22 05:11

niton


Dim outapp As Outlook.Application
Set outapp = CreateObject("outlook.application")

There is no need to create a new Outlook Application instance in the Outlook VBA, simply use the Application property


To reference a folder that is not under default Inbox - example would be

Option Explicit
Public Sub Example()
    Dim olNs As Outlook.NameSpace
    Set olNs = Application.Session

    Dim Digest_Fldr As Outlook.MAPIFolder
    Set Digest_Fldr = olNs.GetDefaultFolder(olFolderInbox) _
                          .Parent.Folders("fldSpamDigest")

    Dim Items As Outlook.Items
    Set Items = Digest_Fldr.Items

    Dim i As Long
    For i = Items.Count To 1 Step -1
        DoEvents
        Debug.Print Items(i).Subject
    Next

End Sub
like image 43
0m3r Avatar answered Nov 02 '22 05:11

0m3r