Check if an outlook folder exists; if not create it

user3773508 picture user3773508 · Nov 18, 2018 · Viewed 7.2k times · Source

Im trying to check if a folder exists; if it does not then create it. The below is just throwing a run-time error.

 Sub AddClose()
 Dim myNameSpace As Outlook.NameSpace
 Dim myFolder As Outlook.Folder
 Dim myNewFolder As Outlook.Folder
 Set myNameSpace = Application.GetNamespace("MAPI")
 Set myFolder = myNameSpace.GetDefaultFolder(olFolderInbox)

            If myFolder.Folders("Close") = 0 Then
                myFolder.Folders.Add("Close").Folders.Add ("EID1")
                myFolder.Folders("Close").Folders.Add ("EID2")
                myFolder.Folders("Close").Folders.Add ("EID3")

            End If
End Sub

However, If the folder exists then the below works...

If myFolder.Folders("Close") > 0 Then
    MsgBox "Yay!"            
End If

Why? What can I do to correct the problem?

Answer

Dmitry Streblechenko picture Dmitry Streblechenko · Nov 19, 2018

Firstly, you are comparing the result of the myFolder.Folders("Close") call (which is supposed to return a MAPIFolder object) with an integer (0). You need to use Is Nothing or Is not Nothing operator.

Secondly, MAPIFolder.Folders.Item() raises an exception if the folder with a given name is not found. You need to trap that exception (as ugly as it is in VBA) and either check the Err.Number value or check that the return object is set:

On Error Resume Next
set subFolder = myFolder.Folders.Item("Close")
if subFolder Is Nothing Then
  set subFolder = myFolder.Folders.Add("Close")
End If