I wrote a comment to the question, in which I said that the right answer is AnswerC in the tutorial linked in the comment by @TonyDallimore. The tutorial is very helpful for understanding the object model to see how to access Outlook folders by name. But there is one line of code from the answer here by @koolprasad2003 :
Set olFldr = olNs.Folders("folder1").Folders("fol2")
that gave me an idea of how to simplify Tony's AnswerC:
Function oOutlookFolder(sOutlookFolder As String, sDelim As String) As MAPIFolder
' Return the MS Outlook folder object represented by the structure of folder names in sOutlookFolder.
' sOutlookFolder has the structure "folder1|folder2|...|folderN" if sDelim = "|".
' Adapted from combination of subs AnswerC2() and AnswerC3() in:
' www.stackoverflow.com/questions/8697493/update-excel-sheet-based-on-outlook-mail/#8699250
' and
' www.stackoverflow.com/questions/11151811/reference-a-folder-by-name/#34282145
Dim oFolders As Folders, oFolder As MAPIFolder, nCharPosn As Byte, _
sFolder As String, sChildren As String, bFirst As Boolean
Set oFolders = CreateObject("Outlook.Application").GetNamespace("MAPI").Folders
sChildren = sOutlookFolder
bFirst = True
nCharPosn = 1
While nCharPosn <> 0
nCharPosn = InStr(sChildren, sDelim)
sFolder = Mid(sChildren, 1, IIf(nCharPosn = 0, 100, nCharPosn - 1))
If (bFirst) Then
Set oFolder = oFolders(sFolder)
Else
Set oFolder = oFolder.Folders(sFolder)
End If
bFirst = False
If (nCharPosn <> 0) Then sChildren = Mid(sChildren, nCharPosn + 1)
Wend
Set oOutlookFolder = oFolder
End Function ' oOutlookFolder()
That function basically replaces Tony's sub AnswerC2()
, as well as AnswerC3()
, which is called by AnswerC2()
, as well as recursively by itself. Therefore, in Tony's code for AnswerC1()
, AnswerD()
, and AnswerE()
, you can replace:
Call AnswerC2(FolderTgt, FolderNameTgt, "|")
with:
set FolderTgt = oOutlookFolder(FolderNameTgt, "|")
I have tested this successfully in Outlook 2021.
There are two weaknesses of my code for oOutlookFolder()
. First, the while loop is inelegant since it checks the value of nCharPosn
three times. And second, the function has no error checking and will crash if sOutlookFolder
doesn't represent an existing Outlook folder. I would be happy for others to improve the code.