Skip to main content

如何在Outlook中獲取資料夾列表?

Author: Siluvia Last Modified: 2025-05-13

有時候,導航窗格中所有郵件資料夾(包括建立的個人資料夾)的樹狀結構可以在工作期間為Outlook用戶提供幫助。為了快速列出整個樹狀結構的資料夾,VBA代碼可以幫助您。在本教程中,您可以學習如何使用VBA代碼輕鬆獲取資料夾列表。

使用VBA代碼在Outlook中獲取資料夾列表


使用VBA代碼在Outlook中獲取資料夾列表

要使用VBA代碼在Outlook中獲取資料夾列表,請按照以下步驟操作。

1. 按下鍵盤上的「Alt」+「F11」鍵以打開「Microsoft Visual Basic for Applications」窗口。

2. 然後雙擊「Project1」>「Microsoft Outlook Object」>「ThisOutlookSession」以打開「Project1 – ThisOutlookSession」窗口。參見截圖:

the Project1 – ThisOutlookSession window

3. 然後將以下VBA代碼複製並粘貼到Project1 – ThisOutlookSession窗口中。

VBA:在Outlook中獲取資料夾列表

Option Explicit
Sub GetFoldersList()
    On Error GoTo On_Error
    
    Dim Report As String
    Dim Folder As Outlook.Folder
       
    For Each Folder In Application.Session.Folders
        Report = Report & "---------------------------------------------------------------------------" & vbCrLf
        Call RecurseFolders(Folder, "", Report)
    Next
    Call CreateReportEmail("Outlook Folders List", Report)
    
Exiting:
    Exit Sub
On_Error:
    MsgBox "error=" & Err.Number & " " & Err.Description
End Sub
Sub RecurseFolders(CurrentFolder As Outlook.Folder, TabChars, ByRef Report As String)
    Dim SubFolder As Outlook.Folder
    Dim FolderName, StoreName As String
    
    FolderName = CurrentFolder.Name
    StoreName = CurrentFolder.Store.DisplayName
    
    Report = Report & TabChars & FolderName & " (Store: " & StoreName & ")" & vbCrLf
    
    For Each SubFolder In CurrentFolder.Folders
        Call RecurseFolders(SubFolder, TabChars & vbTab, Report)
    Next SubFolder
End Sub
Sub CreateReportEmail(Title As String, Report As String)
    Dim aMail As MailItem
    
    Set aMail = Application.CreateItem(olMailItem)
        
    aMail.Subject = Title
    aMail.Body = Report
    
    aMail.Display
End Sub

4. 按下鍵盤上的「F5」鍵開始運行VBA代碼。

5. 此時會彈出一個「宏」對話框,請點擊「執行」按鈕。

a Macro dialog box

6. 等待宏運行完成。然後,所有電子郵件資料夾的列表會立即顯示在新建的消息窗口中。您可以輕鬆列印出來。參見截圖:

the list of all your email folders is listed out in a created new message window

便簽:此VBA代碼適用於Outlook 2007、2010和2013。