0
votes

I have created a VBA subroutine to list any and all sub-folders that have "NNN" text in the name in a list-box on a userform - I have loads of sub-folders and finding the right one is therefore time consuming. This routine works perfectly.

However, what I now want to do is to double-click on a list-box item and it "selects" the folder in the folder hierarchy to save me the time to locate it manually (it could be several levels down).

I have a snippet that does this:

Public Sub GetItemsFolderPath()
  Dim obj As Object
  Dim F As Outlook.MAPIFolder
  Dim Msg$
  Set obj = Application.ActiveWindow
  If TypeOf obj Is Outlook.Inspector Then
    Set obj = obj.CurrentItem
  Else
   Set obj = obj.Selection(1)
  End If
  Set F = obj.Parent
  Msg = "The path is: " & F.FolderPath & vbCrLf
  Msg = Msg & "Switch to the folder?"
  If MsgBox(Msg, vbYesNo) = vbYes Then
   Set Application.ActiveExplorer.CurrentFolder = F
  End If
End Sub

However, if I try and replace "F" with a folder path which is just a string, it fails. So my question is, how can I select the folder using just a string for the folder path like "[email protected]\Inbox\03_Group Finance\00_Organization Chart"

Thanks

2

2 Answers

0
votes

I tried this little simple thing to return a folder from a path:

Function FolderFromPath(FolderPath As String) As Folder
    Dim F As Folder
    Dim arrFolders() As String
    Dim i As Integer
    Set myNamespace = Application.GetNamespace("MAPI")

    Set F = myNamespace.GetDefaultFolder(olFolderInbox)
    arrFolders = Split(FolderPath, "\")
    For i = 4 To UBound(arrFolders)
        Set F = F.Folders(arrFolders(i))
    Next
    Set FolderFromPath = F
 End Function

It starts from your inbox (which perhaps isn't what you need), and then splits the path and goes into each folder in the path.

Update after comment I forgot to show how to use it. You can do it like this:

Path = "\\[email protected]\Inbox\Folder1\Folder2"
Set Application.ActiveExplorer.CurrentFolder = FolderFromPath(Path)
0
votes

The method described by Sam will do what you want. There is a small problem with the code. The index starts to far along the path. 4 should be 2 if the initial reference is to the Inbox.

Function FolderFromPath(FolderPath As String) As Folder

    Dim F As Folder
    Dim arrFolders() As String
    Dim i As Long

    arrFolders = Split(FolderPath, "\")

    ' Initial reference is to the mailbox - array element 0
    Set F = Session.Folders(arrFolders(0))

    ' The next folder is array element 1
    For i = LBound(arrFolders) + 1 To UBound(arrFolders)
        Set F = F.Folders(arrFolders(i))
    Next

    Set FolderFromPath = F

 End Function


Public Sub GetItemsFolderPath_Test()

    Dim FPath As String

    FPath = "[email protected]\Inbox\03_Group Finance\00_Organization Chart"

    Set ActiveExplorer.CurrentFolder = FolderFromPath(FPath)

End Sub