简体   繁体   中英

Reference a folder not under the default inbox

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

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
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM