I can’t figure why this won’t work. This code successfully gets the chosen Outlook folder and all subfolders into a collection, but if I activate the commented Key (in red) Collection field, I get a key duplication error, which I don’t see in the created Note as the code is now written. Can anybody see my problem?
Public colFolders As Collection
Public Function AllFoldersCollection(ByRef objRootFolder As MAPIFolder)
Set colFolders = New Collection
Call GetFoldersCollection(objRootFolder)
End Function
Private Function GetFoldersCollection(ByRef objStartFolder As MAPIFolder)
Dim objFolder As MAPIFolder
For Each objFolder In objStartFolder.Folders
colFolders.Add Item:=objFolder ‘, Key:=foldertree(objFolder)
If objFolder.Folders.Count > 0 Then _
Call GetFoldersCollection(objFolder) ‘recurse this function to subfolders
Next objFolder
Set objFolder = Nothing
End Function
Public Function foldertree(objFolder As MAPIFolder) As String
Do
foldertree = “” & objFolder.Name & foldertree
If UCase(objFolder.Parent) = “MAPI” Then Exit Do
Set objFolder = objFolder.Parent
Loop
End Function
From here down is code to test the collection:
Sub testfolderscol()
Dim nsNS As NameSpace
Dim fldrSel As MAPIFolder
Dim allSubFolders As New Collection
Dim itmNote As NoteItem
Dim lngC As Long
Dim strText As String
Set nsNS = Application.GetNamespace(“MAPI”)
Set fldrSel = nsNS.PickFolder
Call AllFoldersCollection(fldrSel)
Set allSubFolders = colFolders
If Not allSubFolders Is Nothing Then
Set itmNote = OpenNewNoteItem()
For lngC = 1 To allSubFolders.Count
‘What I want to do is the next commented line …
‘ strText = strText & allSubFolders(lngC).Key & vbLf ‘.Name & vbLf
‘but I have to do this …
strText = strText & foldertree(allSubFolders(lngC)) & vbLf
Next lngC
itmNote.Body = “Folder List” & vbLf & vbLf & strText
itmNote.Display
End If
Set allSubFolders = Nothing
Set fldrSel = Nothing
Set nsNS = Nothing
End Sub
Private Function OpenNewNoteItem() As NoteItem
Dim objNoteitem As NoteItem
Set objNoteitem = Outlook.Application.CreateItem(OLNoteItem)
Set OpenNewNoteItem = objNoteitem
End Function