2

I'm new to Outlook VBA and having a tough time figuring out how to set my subfolder in the code below. I have been trouble shooting this all day. Not sure what I'm missing.

Sub DeleteOlderThan6months()

Dim oFolder As Folder
Dim Date6months As Date
Dim ItemsOverMonths As Outlook.Items

Dim DateToCheck As String

Date6months = DateAdd("d", -1, Now())
Date6months = Format(Date6months, "mm/dd/yyyy")


Set oFolder = oFolder.Folders("My@email.com").Folders("Inbox").Folders("Zip Files") 

DateToCheck = "[Received] <= """ & Date6months & """"

Set ItemsOverMonths = oFolder.Items.Restrict(DateToCheck)

For i = ItemsOverMonths.Count To 1 Step -1
ItemsOverMonths.Item(i).Delete
Next


Set ItemsOverMonths = Nothing
Set oFolder = Nothing


End Sub
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
OAD
  • 35
  • 5
  • 1
    Possible duplicate of [Using visual basic to access subfolder in Inbox?](https://stackoverflow.com/questions/8322432/using-visual-basic-to-access-subfolder-in-inbox) – niton Jul 19 '17 at 11:22

2 Answers2

1
set Inbox = Application.Session.GetDefaultFolder(olFolderInbox)
set oFolder = Inbox.Folders.Item("Zip Files") 
Dmitry Streblechenko
  • 62,942
  • 4
  • 53
  • 78
1

This should do it, see how i set the subfolder

Option Explicit
Sub DeleteOlderThan6months()
    '//  Declare variables
    Dim oFolder As Folder
    Dim Date6months As Date
    Dim ItemsOverMonths As Outlook.Items
    Dim DateToCheck As String
    Dim olNs As Outlook.NameSpace
    Dim Inbox  As Outlook.MAPIFolder
    Dim oItem As Object
    Dim i As Long

    '// set your inbox and subfolder
    Set olNs = Application.GetNamespace("MAPI")
    Set Inbox = olNs.GetDefaultFolder(olFolderInbox)
    Set oFolder = Inbox.Folders("Zip Files")

    Date6months = DateAdd("d", -1, Now())
    Date6months = Format(Date6months, "mm/dd/yyyy")

    DateToCheck = "[Received] <= """ & Date6months & """"
    Set ItemsOverMonths = oFolder.Items.Restrict(DateToCheck)

    '// Loop through the Items in the folder backwards
    For i = ItemsOverMonths.Count To 1 Step -1
        Set oItem = ItemsOverMonths.Item(i)
        If TypeOf oItem Is Outlook.MailItem Then
            Debug.Print oItem.Subject
            oItem.Delete
        End If
    Next

    Set ItemsOverMonths = Nothing
    Set oFolder = Nothing

End Sub
0m3r
  • 12,286
  • 15
  • 35
  • 71