What is the VBA syntax to reference a folder in Outlook 2013?

1

Working on some code to mark items as read when they are moved into my 'Archive' folder which is on the same level as my default folders (Inbox, Sent, etc.). The code below was my initial test using the default deleted items folder. What is the proper syntax so I can reference the items in my Archive folder?

Private WithEvents Items As Outlook.Items

Private Sub Application_Startup()
  Dim Ns As Outlook.NameSpace
  Set Ns = Application.GetNamespace("MAPI")
  Set Items = Ns.GetDefaultFolder(olFolderDeletedItems).Items

End Sub

Private Sub Items_ItemAdd(ByVal Item As Object)
    Item.UnRead = False
    Item.Save
End Sub 

Gryphoenix

Posted 2017-08-30T14:08:20.590

Reputation: 220

1

You will want to change olFolderDeletedItems to a variable you create that uses the reference to the current folder instead. But you can't use GetDefaultFolder unless the folder is an actual default folder and your user created Archive directory is not.

– Ramhound – 2017-08-30T14:18:07.693

1

look at the Folders collection documentation: https://msdn.microsoft.com/en-us/library/office/aa210918(v=office.11).aspx

– Yorik – 2017-08-30T14:21:56.060

@Ramhound - if my Archive folder is on the same level as olFolderInbox, do I need to still reference it by .Folders("Archive")? – Gryphoenix – 2017-08-30T15:42:56.700

@Yorik thanks. Is the example provided referencing a sub-folder? – Gryphoenix – 2017-08-30T15:43:35.350

I haven't used it, but what I see there is them setting the current folder or namespace (a "root folder"), and then using Folders collection to reference child folders. I also see there that if you know the name of the child folder, you can use that as a string-literal instead of needing to identify its numeric index. You could try emitting the Folder().Name property in a foreach – Yorik – 2017-08-30T15:59:24.787

@Gryphoenix - What does the documentation for API call, Folders, indicate? As I pointed out GetDefaultFolders won't work on a user created folder though. – Ramhound – 2017-08-30T16:06:07.357

Answers

1

Found that it is easier to invoke the PickFolder method rather than try and figure out how to reference the Archive folder. Now my code functions properly.

Option Explicit

Private WithEvents Items As Outlook.Items

Private Sub Application_Startup()
  Dim Ns As Outlook.NameSpace
  Dim myFolder As Outlook.Folder


  Set Ns = Application.GetNamespace("MAPI")

  Set myFolder = Ns.PickFolder

  Set Items = myFolder.Items

End Sub

Private Sub Items_ItemAdd(ByVal Item As Object)
    Item.UnRead = False
    Item.Save
End Sub

Gryphoenix

Posted 2017-08-30T14:08:20.590

Reputation: 220