从文件夹路径获取 Folder 对象

本主题演示的功能可接受文件夹路径,并返回一个对应于指定文件夹的 Folder 对象。 例如,如果提供的文件夹路径为"Mailbox - Dan Wilson\Inbox\Customers",则 TestGetFolder 过程中的代码将显示对应于位于 Dan Wilson 的收件箱下的 Customers 文件夹的 Folder 对象(如果该收件箱下存在 Customers 文件夹)。 如果 Customers 文件夹不存在,则 GetFolder 将返回 Nothing

Function GetFolder(ByVal FolderPath As String) As Outlook.Folder 
    Dim TestFolder As Outlook.Folder 
    Dim FoldersArray As Variant 
    Dim i As Integer 
 
    On Error GoTo GetFolder_Error 
    If Left(FolderPath, 2) = "\\" Then 
        FolderPath = Right(FolderPath, Len(FolderPath) - 2) 
    End If 
    
    'Convert folderpath to array 
    FoldersArray = Split(FolderPath, "\") 
    Set TestFolder = Application.Session.Folders.item(FoldersArray(0)) 
    If Not TestFolder Is Nothing Then 
        For i = 1 To UBound(FoldersArray, 1) 
            Dim SubFolders As Outlook.Folders 
            Set SubFolders = TestFolder.Folders 
            Set TestFolder = SubFolders.item(FoldersArray(i)) 
            If TestFolder Is Nothing Then 
                Set GetFolder = Nothing 
            End If 
        Next 
    End If 
     
   'Return the TestFolder 
    Set GetFolder = TestFolder 
    Exit Function 
 
GetFolder_Error: 
    Set GetFolder = Nothing 
    Exit Function 
End Function 
 
Sub TestGetFolder() 
    Dim folder As Outlook.Folder 
    Set folder = GetFolder ("\\Mailbox - Dan Wilson\Inbox\Customers") 
    If Not(folder Is Nothing) Then 
        folder.Display 
    End If 
End Sub

支持和反馈

有关于 Office VBA 或本文档的疑问或反馈? 请参阅 Office VBA 支持和反馈,获取有关如何接收支持和提供反馈的指南。